Sie sind auf Seite 1von 42

18

Creating the Persistence Layer


with TopLink

Copyright © 2007, Oracle. All rights reserved.


Objectives

After completing this lesson, you should be able to do


the following:
• Create a TopLink Object-Relational Map
• Develop persistent objects by using TopLink
• Identify a named query and explain how it can be
used effectively in an application
• Define a named query
• Execute named queries at run time
• Explain the role of the TopLink Session

18-2 Copyright © 2007, Oracle. All rights reserved.


What Is TopLink?

• Object-Relational Mapping (ORM) solution:


Java  RDBMS
• Development
– Define mappings between model and schema
– Configure: Queries, caching, locking, clustering,
and so on
• Run time
– Metadata driven from defined XML metadata
– Optimized database read and write access
– Management, logging, and profiling

18-3 Copyright © 2007, Oracle. All rights reserved.


Benefits of TopLink

Performance and scalability


• Flexible query for optimized data access
• Minimizes transaction costs
• Configurable caching with clustered coordination
Developer productivity
• Simplified mapping using graphical editors
• Generation and auto-map wizards
• Error detection and warning during development
Flexibility
• Support of leading databases and Java containers
• Java EE and Java SE

18-4 Copyright © 2007, Oracle. All rights reserved.


Where Does TopLink Fit?
Presentation interface

Application logic Business entities

Java EE services
TopLink CMP/
BMP
JTA

Connection
Mapping editors pools

JDBC JDBC JCA

Data source

XDB EIS

18-5 Copyright © 2007, Oracle. All rights reserved.


TopLink Objects

• Plain Old Java Objects (POJOs)


• Objects mapped for each database table
• Objects with get() and set() methods
• Allows for query and DML in the object model,
rather than SQL
• Configured in the TopLink Map

18-6 Copyright © 2007, Oracle. All rights reserved.


Extensions to JPA

• Persistence unit properties:


– Logging
– Database and Server Platform
– Cache configuration
– Schema generation
• Query hints
• Lazy loading of One-To-One and Many-To-One

18-7 Copyright © 2007, Oracle. All rights reserved.


TopLink Design Time
Mapping Editor

Persistent Metadata
objects
Session XML

*
Map XML Schema
Application
development development

18-8 Copyright © 2007, Oracle. All rights reserved.


TopLink Mapping Editor

• Contains mappings for Java


objects
• Is accessible through the
JDeveloper interface
• Shows each TopLink object
• Includes each attribute

18-9 Copyright © 2007, Oracle. All rights reserved.


Mapping Types

A mapping type addresses ways in which an object’s


data and relationships are stored in the database.
• Direct-to-field: Enables data in an instance
variable to be stored directly into a column in a
table
• Type conversion: Enables data of one type to be
stored in a table as another type
– “age” may be a string in the object, but stored as
NUMBER in the table
• One-to-one: Describes how a one-to-one
relationship between two classes is stored in the
database

18-10 Copyright © 2007, Oracle. All rights reserved.


TopLink Caching

Persistent objects cached by “identity”


• Identity == Primary Key field(s)
Benefits:
• Avoids unnecessary database trips
• Avoids re-building objects from data
• Enables in-memory query processing
• Can be coordinated in clustered deployments
Developer tasks:
• Application-specific cache configuration to
optimize performance and minimize stale data
• Leverage-locking to avoid data corruption

18-11 Copyright © 2007, Oracle. All rights reserved.


Transaction Features and Support

Unit of Work provides Java abstraction.


Minimizes database interactions:
• Calculates the minimal change set at commit time
(deferred write)
• Only the minimal DML issued
Respects database integrity:
• Orders INSERT, UPDATE and DELETE statements
“Unit Of Work” fully supports Java Transaction
API (JTA).

18-12 Copyright © 2007, Oracle. All rights reserved.


Performance and Tuning Options

• Minimal Writes, Updates • “Just in Time” Reading


• Batch Reading, Writing • Automatic change detection
• SQL Ordering • Caching policies and sizes
• Parameterized SQL (binding)
• Transformation Support
• Preallocation of sequence
• Existence Checks numbers
• Stored Procedures • Cache Coordination
• Statement Caching • Optimistic, Pessimistic locking
• Scrolling Cursors • Joining object retrieval
optimization
• Projection Queries
• In memory querying
• Partial Attribute Queries • Dynamic Queries
• Bulk Update Queries • Optimized Change Tracking

18-13 Copyright © 2007, Oracle. All rights reserved.


TopLink JAXB

Provides complete Object-XML mapping capabilities


• Enable developers to work with XML as objects
• Graphical user interface (GUI) tool for mapping
• Efficiently produce and process SOAP messages
Supports Object-XML standard - JAXB
• Provides additional flexibility to enable complete
control on how objects are mapped

Databases XML Data

18-14 Copyright © 2007, Oracle. All rights reserved.


Creating a TopLink Persistence Layer

1. Create TopLink Java objects from tables.


2. Create a TopLink session object.
3. Create a test client.
4. Access TopLink session objects from a client.

18-15 Copyright © 2007, Oracle. All rights reserved.


Creating TopLink Objects

18-16 Copyright © 2007, Oracle. All rights reserved.


Creating TopLink Objects

18-17 Copyright © 2007, Oracle. All rights reserved.


What Is a Named Query?

• A named query is defined during development and


is registered with a session or a descriptor by
using a unique name.
• At run time, the query can be retrieved and
executed by name.
• Advantages of building named queries:
– Can be used many times in an application, after
they are built
– Enables complex behavior to be added to the query
– Enables parameters to be passed into the query
expression

18-18 Copyright © 2007, Oracle. All rights reserved.


Building Named Queries

Build named queries by using the JDeveloper TopLink


Mapping Editor:
• Supports queries with TopLink Expressions, EJB
QL, and SQL query
• Supports parameters in query expressions
• Enables some query options to be set

18-19 Copyright © 2007, Oracle. All rights reserved.


Query Editor

18-20 Copyright © 2007, Oracle. All rights reserved.


Adding Queries Using the Mapping Editor

• Click the Format tab.


• Select Expression.
• Click Edit.

18-21 Copyright © 2007, Oracle. All rights reserved.


Creating a Java Console Test Client

Create a test client to


access TopLink objects.

18-22 Copyright © 2007, Oracle. All rights reserved.


The Test Client

session.login();
Collection results =
session.readAllObjects(Products.class);
for (Iterator itr =
results.iterator();itr.hasNext();) {
printObjectAttributes(itr.next(), session);
}

18-23 Copyright © 2007, Oracle. All rights reserved.


Building Query Objects in Code

• Create reusable query objects


• Most common types:
– ReadAllQuery and ReadObjectQuery
Query type

Class ReadAllQuery q = new ReadAllQuery();


being q.setReferenceClass(Employee.class)
queried q.setSelectionCriteria(anExpression);

Selection criteria:
Defined by using TopLink
Expression Framework, EJB
QL, or SQL

18-24 Copyright © 2007, Oracle. All rights reserved.


Expressions

• Expressions have a root context that is defined by


the reference class of the query.
• You can define path expressions by using get() to
obtain attributes relating to the root context object:

ReadAllQuery q = new ReadAllQuery();


q.setReferenceClass(Employee.class);
Expression exp = emp.get(“lastName”).equal(“Smith”);

Conditional
expression
“Smith” operator

18-25 Copyright © 2007, Oracle. All rights reserved.


TopLink Support for Query Expressions

TopLink expressions:

ExpressionBuilder bldr = new ExpressionBuilder();


Expression exp = bldr.get(“lastName”).equal(“Smith”);
q.setSelectionCriteria(exp);

EJB Query Language (EJB QL):

q.setEJBQLString(
“select object(e) from employee e where ” +
“e.lastName = ‘Smith’”);

SQL:
q.setSQLString(
“SELECT * FROM EMPLOYEE e WHERE e.L_NAME = ‘Smith’”);

18-26 Copyright © 2007, Oracle. All rights reserved.


Query Object: Example

Building and executing a query:

// This type of query returns a Vector of objects


ReadAllQuery q = new ReadAllQuery();
q.setReferenceClass(Employee.class);
ExpressionBuilder bldr = new ExpressionBuilder();
Expression exp =
bldr.get(“lastName”).equal(“Smith”);
// Set query expression or query logic
q.setSelectionCriteria(exp);
// Customize query by adding ordering to results
q.addAscendingOrdering(“firstName”);
// Execute query
List<Employees> employees =
(List<Employees>)session.executeQuery(q);

18-27 Copyright © 2007, Oracle. All rights reserved.


Using Sequences

• TopLink uses either:


– Sequence Table or
– Native Sequences
• Select “Use
Sequencing” on
Descriptor Info.
• Enter:
– Table name and
column, or
– Sequence name

18-28 Copyright © 2007, Oracle. All rights reserved.


TopLink Sessions

18-29 Copyright © 2007, Oracle. All rights reserved.


Role of the Session

• A session provides the Java application with an


interface to the relational database.
• TopLink services are invoked through the session.
Java application (objects)

TopLink session

JDBC
JDBC
SQL rows

18-30 Copyright © 2007, Oracle. All rights reserved.


POJO-Based Session Facade Methods

mergeEntity()

persistEntity()

refreshEntity()

removeEntity()

18-31 Copyright © 2007, Oracle. All rights reserved.


Unit of Work

• Unit of Work (UOW) provides object-level


transaction functionality.
– Manages changes that are made to persistent
objects
– Commits these changes to the database as one
atomic operation
• If error occurs during UOW commit, then:
– The database is rolled back
– Changes that are made to all objects in the UOW
are rolled back to their original state

18-32 Copyright © 2007, Oracle. All rights reserved.


Unit of Work

• Transaction created only at UOW commit time


– Results in short-running transactions
• Updates only attributes that have changed
• Rolls back both the objects and the database if
something goes wrong during commit
• Proper commit order maintained by the UOW. At
commit time, the UOW:
– Begins the database transaction
– Performs minimal update to objects that have
changed
– Commits the transaction

18-33 Copyright © 2007, Oracle. All rights reserved.


Unit of Work: Life Cycle

18-34 Copyright © 2007, Oracle. All rights reserved.


Unit of Work: Example

// Acquire UOW from a database session


UnitOfWork uow = getSession().acquireUnitOfWork();
// Read an object
Employee employeeOriginal =
(Employee)getSession().readObject(Employee.class);
// Register object -- a working copy is returned
Employee employeeWorkingCopy =
(Employee)uow.registerObject(employeeOriginal);
// Update working copy
employeeWorkingCopy.setFirstName("Geoff");
// commit; transaction created and SQL executed
uow.commit();

SQL optimized to update only what has changed:


UPDATE EMPLOYEE SET F_NAME = 'Geoff' WHERE (EMP_ID = 8)

18-35 Copyright © 2007, Oracle. All rights reserved.


ADF Model Databinding and TopLink

ADF Model:
• Provides a wrapper and
abstraction for business
services
• Enables you to work the
same way with any UI and
any business services
• Decouples UI
from back-end
business
services
• Provides drag-
and-drop
databinding
18-36 Copyright © 2007, Oracle. All rights reserved.
Data Control Palette

Is a visual representation of your business service that


contains:
• Methods
• Parameters and results
• Attributes
• Collections
• Built-in operations

18-37 Copyright © 2007, Oracle. All rights reserved.


Creating a TopLink Data Control

• From the Applications Navigator:


– Select Create Data Control in the component’s
shortcut menu.
OR
– Drag the component to the Data Control Palette.
• Use the Data Control wizards (new in 10.1.3).

18-38 Copyright © 2007, Oracle. All rights reserved.


Bindings

• Define the interaction between a view or controller


component and the data control
• Are created automatically when you drag a
component from the Data Control Palette to a page
or panel
• Can also be created in the Structure window
E-mail: neena.kochhar@

Name: Kochhar

18-39 Copyright © 2007, Oracle. All rights reserved.


Summary

In this lesson, you should have learned how to:


• Create a TopLink Object-Relational mapping
• Develop persistence objects by using TopLink
• Identify a named query and explain how it can be
used effectively in an application
• Define a named query
• Execute named queries at run time
• Explain the role of the TopLink Session

18-40 Copyright © 2007, Oracle. All rights reserved.


Practice Overview:
Creating a TopLink Persistence Layer

This practice covers the following topics:


• Creating default TopLink POJOs
• Using a query to retrieve data from a POJO
• Creating named queries
• Creating data controls
• Including binding on a JSF

18-41 Copyright © 2007, Oracle. All rights reserved.


18-42 Copyright © 2007, Oracle. All rights reserved.

Das könnte Ihnen auch gefallen