18_Creating the Persistence Layer With TopLink

41
18 Copyright © 2007, Oracle. All rights reserved. Creating the Persistence Layer with TopLink

Transcript of 18_Creating the Persistence Layer With TopLink

Page 1: 18_Creating the Persistence Layer With TopLink

18Copyright © 2007, Oracle. All rights reserved.

Creating the Persistence Layer with TopLink

Page 2: 18_Creating the Persistence Layer With TopLink

18-2 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

Page 3: 18_Creating the Persistence Layer With TopLink

18-3 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

Page 4: 18_Creating the Persistence Layer With TopLink

18-4 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

Page 5: 18_Creating the Persistence Layer With TopLink

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

Where Does TopLink Fit?

Data source

TopLink

Presentation interface

Application logic Business entities

Java EE services

JTACMP/BMP

JDBC

Connectionpools

EISXDB

JDBC JCA

Mapping editors

Page 6: 18_Creating the Persistence Layer With TopLink

18-6 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

Page 7: 18_Creating the Persistence Layer With TopLink

18-7 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

Page 8: 18_Creating the Persistence Layer With TopLink

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

TopLink Design Time

Applicationdevelopment

Schemadevelopment

Metadata

Session XML

Map XML*

Persistent objects

Mapping Editor

Page 9: 18_Creating the Persistence Layer With TopLink

18-9 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

Page 10: 18_Creating the Persistence Layer With TopLink

18-10 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

Page 11: 18_Creating the Persistence Layer With TopLink

18-11 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

Page 12: 18_Creating the Persistence Layer With TopLink

18-12 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).

Page 13: 18_Creating the Persistence Layer With TopLink

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

Performance and Tuning Options

• Minimal Writes, Updates • Batch Reading, Writing• SQL Ordering• Transformation Support• Existence Checks • Stored Procedures• Statement Caching• Scrolling Cursors• Projection Queries• Partial Attribute Queries• Bulk Update Queries

• “Just in Time” Reading • Automatic change detection• Caching policies and sizes• Parameterized SQL (binding)• Preallocation of sequence

numbers• Cache Coordination• Optimistic, Pessimistic

locking• Joining object retrieval

optimization• In memory querying• Dynamic Queries• Optimized Change Tracking

Page 14: 18_Creating the Persistence Layer With TopLink

18-14 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

Page 15: 18_Creating the Persistence Layer With TopLink

18-15 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.

Page 16: 18_Creating the Persistence Layer With TopLink

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

Creating TopLink Objects

Page 17: 18_Creating the Persistence Layer With TopLink

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

Creating TopLink Objects

Page 18: 18_Creating the Persistence Layer With TopLink

18-18 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

Page 19: 18_Creating the Persistence Layer With TopLink

18-19 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

Page 20: 18_Creating the Persistence Layer With TopLink

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

Query Editor

Page 21: 18_Creating the Persistence Layer With TopLink

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

Adding Queries Using the Mapping Editor

• Click the Format tab.

• Select Expression.

• Click Edit.

Page 22: 18_Creating the Persistence Layer With TopLink

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

Creating a Java Console Test Client

Create a test client to access TopLink objects.

Page 23: 18_Creating the Persistence Layer With TopLink

18-23 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);

}

Page 24: 18_Creating the Persistence Layer With TopLink

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

Building Query Objects in Code

• Create reusable query objects• Most common types:

– ReadAllQuery and ReadObjectQuery

ReadAllQuery q = new ReadAllQuery();q.setReferenceClass(Employee.class)q.setSelectionCriteria(anExpression);

Query type

Class being

queried

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

Page 25: 18_Creating the Persistence Layer With TopLink

18-25 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”);

“Smith”

Conditional expression operator

Page 26: 18_Creating the Persistence Layer With TopLink

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

TopLink Support for Query Expressions

TopLink expressions:

EJB Query Language (EJB QL):

SQL:

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

q.setEJBQLString(“select object(e) from employee e where ” +

“e.lastName = ‘Smith’”);

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

Page 27: 18_Creating the Persistence Layer With TopLink

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

Query Object: Example

// This type of query returns a Vector of objectsReadAllQuery q = new ReadAllQuery();q.setReferenceClass(Employee.class);ExpressionBuilder bldr = new ExpressionBuilder();Expression exp =

bldr.get(“lastName”).equal(“Smith”);// Set query expression or query logicq.setSelectionCriteria(exp);// Customize query by adding ordering to resultsq.addAscendingOrdering(“firstName”);// Execute queryList<Employees> employees =

(List<Employees>)session.executeQuery(q);

Building and executing a query:

Page 28: 18_Creating the Persistence Layer With TopLink

18-28 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

Page 29: 18_Creating the Persistence Layer With TopLink

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

TopLink Sessions

Page 30: 18_Creating the Persistence Layer With TopLink

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

Java application (objects)

Role of the Session

• A session provides the Java application with an interface to the relational database.

• TopLink services are invoked through the session.

JDBCSQL rows

TopLink session

JDBC

Page 31: 18_Creating the Persistence Layer With TopLink

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

POJO-Based Session Facade Methods

mergeEntity()

persistEntity()

removeEntity()

refreshEntity()

Page 32: 18_Creating the Persistence Layer With TopLink

18-32 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

Page 33: 18_Creating the Persistence Layer With TopLink

18-33 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

Page 34: 18_Creating the Persistence Layer With TopLink

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

Unit of Work: Life Cycle

Page 35: 18_Creating the Persistence Layer With TopLink

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

Unit of Work: Example

// Acquire UOW from a database sessionUnitOfWork uow = getSession().acquireUnitOfWork();// Read an objectEmployee employeeOriginal =

(Employee)getSession().readObject(Employee.class);// Register object -- a working copy is returnedEmployee employeeWorkingCopy =

(Employee)uow.registerObject(employeeOriginal);// Update working copyemployeeWorkingCopy.setFirstName("Geoff");// commit; transaction created and SQL executeduow.commit();

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

SQL optimized to update only what has changed:

Page 36: 18_Creating the Persistence Layer With TopLink

18-36 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

Page 37: 18_Creating the Persistence Layer With TopLink

18-37 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

Page 38: 18_Creating the Persistence Layer With TopLink

18-38 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).

Page 39: 18_Creating the Persistence Layer With TopLink

18-39 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

Page 40: 18_Creating the Persistence Layer With TopLink

18-40 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

Page 41: 18_Creating the Persistence Layer With TopLink

18-41 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