EJB%203.0%20Java%20Persistence%20API%20(JPA)%20with%20Oracle%20TopLink - PowerPoint PPT Presentation

About This Presentation
Title:

EJB%203.0%20Java%20Persistence%20API%20(JPA)%20with%20Oracle%20TopLink

Description:

EJB 3.0 Java Persistence API (JPA) with Oracle TopLink Bill Lyons Systems Architect Hitachi Consulting wlyons_at_hitachiconsulting.com – PowerPoint PPT presentation

Number of Views:258
Avg rating:3.0/5.0
Slides: 52
Provided by: BillL195
Category:

less

Transcript and Presenter's Notes

Title: EJB%203.0%20Java%20Persistence%20API%20(JPA)%20with%20Oracle%20TopLink


1
EJB 3.0 Java Persistence API (JPA) with Oracle
TopLink
  • Bill Lyons
  • Systems Architect
  • Hitachi Consulting
  • wlyons_at_hitachiconsulting.com

2
Introduction
  • Applications using a back end database and a web
    front end are the most common development
    architecture in use today.
  • Persistence frameworks provide a clean way to
    separate presentation logic and business logic
    from database operations.
  • Persistence frameworks help improve database
    performance through the use of a mid-tier cache.
  • The mid-tier improves user experience by caching
    frequently used data for recall without having to
    take a trip to the database.

3
Overview
  • Examine the development of code that manages
    interaction between the database and
    applications.
  • Take a close look at TopLink - an Oracle owned
    persistence framework.
  • Discuss design tradeoffs and common issues
    associated with using a persistence tier.

4
EJB 3.0 Top Link Presentation Goals
  • Develop a high level understanding of J2EE
    design.
  • Understand how persistence frameworks simplify
    development.
  • Understand persistence tier development choices.
  • Understand and be able to develop a simple
    persistence framework using Oracle TopLink.

5
J2EE Overview
6
Application Layout
7
Design artifacts in a typical web based J2EE
application
  • Well follow the Model-View-Controller OO Design
    Pattern

TopLink simplifies the development and
maintenance of the Model portion of an MVC
application.
8
The Persistence Management Problem
  • Relational Databases and Object Oriented
    Languages organize data differently.
  • This makes it difficult for web developers to
    store and retrieve data from a database.
  • JDBC code provides access to the database, but is
    difficult to maintain.
  • JDBC code can be a significant source of
    performance problems if not maintained properly.
  • Persistence frameworks are designed to improve
    performance while standardizing and simplifying
    development.

9
Competing Technologies that solve the persistence
problem
  • Create your own connection pool and write JDBC
    and SQL code ugly!
  • Use a persistence framework
  • Hibernate
  • Spring
  • JDO
  • BC4J
  • TopLink
  • and many others

10
TopLink recommended for new development efforts
  • Has the largest installed base
  • Easy to use and maintain
  • Rich feature set
  • Easy for Java developers to learn very well
    documented
  • Easy for DBAs to understand
  • Supported by Oracle
  • However, probably not appropriate for Oracle Apps
    integration.
  • Design Limitation/Recommendation Use Only 1
    persistence framework/strategy per database table.

11
Demo Development Environment
  • Database
  • Oracle XE
  • Integrated Development Environment
  • Oracle JDeveloper 10.1.3.3
  • Application Server
  • Oracle 10g Application Server (OC4J) (embedded
    in JDeveloper for todays demo)
  • Development Platform
  • Windows, Unix, Mac

12
Typical TopLink Project Artifacts
  • A JDeveloper Database Connection
  • TopLink Plain old Java Objects (POJOs) that
    represent table metadata and table row instances
    from an Oracle database
  • An EJB session bean that allows users to connect
    to the persistence tier and perform data
    operations.
  • Developer constructed queries.
  • Code to test out the persistence implementation
    using an EJB test client.

13
TopLink Getting Started
  • Download and install database (or connect to one)
  • Download and install JDeveloper 10.1.3.3
  • Build tables, indexes, sequences and constraints
    on the database (Well use the Oracle SRDemo
    today as an example)
  • SRDemo Tables, Indexes and Sequences are
    generated by running the build.sql script bundled
    with SRDemo
  • Be sure to get the SRDemo for TopLink not
    ADF/BC or SRDemo for 4GL. There are different
    versions out there

14
TopLink Getting Started (cont.)
  • Create a Connection from JDeveloper to the
    Database.
  • Create a new TopLink project and workspace in
    JDeveloper.
  • Run the TopLink wizard to create EJB 3.0 JPA
    Entity Objects and an EJB Session Bean.
  • Refine the design if necessary.
  • Deploy to an application server.
  • Write a test client to test out the
    implementation.
  • If everything works, version the source code
    along with the database DDL.

15
SRDemo Schema
16
TopLink My First Persistence Tier
  • Start Database
  • Start JDeveloper
  • Create a Connection to the Database in JDeveloper
  • Create an Application and Workspace in JDeveloper

17
Create a new Application and Workspace in
JDeveloper
You can type anything for Application Name and
Directory Name. In general, JDeveloper like most
Java Development Environments will behave
inconsistently with spaces between characters so
dont use them in names or directory
paths. Choose Web Application JSF, EJB, TopLink
for the Application Template and click OK.
18
Create EJB 3.0 Entity Objects using TopLink
  • A TopLink Entity Object will be created for each
    table and view referenced
  • Entity Objects define database tables and
    operations that can be performed on entity rows.
  • Database views and synonyms are also viable
    selections for TopLink entities.
  • TopLink can reference database sequences or
    stored procedures to populate columns

19
Using JDeveloper wizards to create TopLink
objects using EJB 3.0 APIs
Be sure to choose EJB and Entities from Tables
(JPA/EJB 3.0) when creating the persistence tier
20
Examining the Generated TopLink Entity Objects
A Java Entity object will be created for every
table that is selected in the wizard. It is
possible to also select database views and
synonyms for generation. The Entity object
contains table metadata, get/set methods for each
column and named queries for the Entity. A
separate Java object will be created for querying
and enforcing primary key constraints.
21
Examining the Generated Java Source Code Table
Code
  • _at_Entity
  • _at_NamedQuery( name "ExpertiseAreas.findAll",
  • query "select o from ExpertiseAreas o" )
  • _at_Table( name "EXPERTISE_AREAS" )
  • _at_IdClass( ExpertiseAreasPK.class )
  • public class ExpertiseAreas implements
    Serializable
  • _at_Column( name"EXPERTISE_LEVEL", nullable
    false )
  • private String expertiseLevel
  • private String notes
  • _at_Id
  • _at_Column( name"PROD_ID", nullable false,
    insertable false, updatable false )
  • private Long prodId
  • _at_Id
  • _at_Column( name"USER_ID", nullable false,
    insertable false, updatable false )
  • private Long userId
  • _at_ManyToOne
  • _at_JoinColumn( name "PROD_ID",
    referencedColumnName "PROD_ID" )
  • private Products products

22
Examining the Generated Java Source Code Column
Code
  • //
  • public String getExpertiseLevel()
  • return expertiseLevel
  • public void setExpertiseLevel( String
    expertiseLevel )
  • this.expertiseLevel expertiseLevel
  • public String getNotes()
  • return notes
  • public void setNotes( String notes )
  • this.notes notes
  • public Long getProdId()
  • return prodId

23
Create a class diagram from the Entity Objects
From inside of the rmoug Model project right
click and choose New The New Gallery
appears. Choose Diagrams Database Diagram Name
the diagram SRDemo class diagram. Then drag and
drop the Java Beans that we created in the
previous step. Arrange the diagram objects so
that all elements are visible.
24
JDeveloper class diagram
25
Build a session bean to expose the Entities and
provide session functionality
From the New Gallery choose Business Tier, EJB,
Session Bean (EJB 1.1/2.x/3.0) Accept all
defaults.
26
Purpose of the Session Bean
  • Encapsulates all of the behavior needed by a java
    service (could be web, swing client, or web
    service) so that a client can connect and query
    objects out of the persistence tier.
  • Deployed with our POJOs to an EJB container.
  • Well use OC4J a local application server
    embedded in JDeveloper that is fully EJB 3.0
    compliant

27
Examining the Session Bean Generated Source Code
  • _at_Stateless( name"SessionEJB" )
  • public class SessionEJBBean implements
    SessionEJB, SessionEJBLocal
  • _at_PersistenceContext( unitName"Model" )
  • private EntityManager em
  • public Object mergeEntity( Object entity )
  • return em.merge(entity)
  • public Object persistEntity( Object entity )
  • em.persist(entity)
  • return entity
  • / ltcodegtselect o from ExpertiseAreas olt/codegt
    /
  • public ListltExpertiseAreasgt queryExpertiseAreasF
    indAll()
  • return em.createNamedQuery("ExpertiseAreas.fin
    dAll").getResultList()

28
Build a simple test client
To create a test client right click on the
SessionEJBBean.java that we generated earlier in
the project and choose New Sample Java Client
29
Examine the Generated Code for the Test EJB Client
  • public class SessionEJBClient
  • public static void main( String args )
  • try
  • final Context context getInitialContext()
  • SessionEJB sessionEJB (SessionEJB)context.
    lookup("SessionEJB")
  • System.out.println( sessionEJB.queryExpertiseAre
    asFindAll( ) )
  • // Call other methods of the Remote object
    to access the EJB
  • // sessionEJB.mergeEntity( expertiseAreas
    )
  • // sessionEJB.persistEntity( expertiseAreas
    )
  • // sessionEJB.removeExpertiseAreas(
    expertiseAreas )
  • catch ( Exception ex )
  • ex.printStackTrace()

30
Testing it all out
  • Run the SessionEJBBean
  • This deploys the SessionEJBBean, connection and
    Entity objects to the OC4J container embedded in
    JDeveloper.
  • Run the SessionEJBClient
  • The client will connect to the Web Application
    Server, locate the SessionEJBBean and execute
    methods on the remote session bean.
  • Remember, you must run the SessionEJBBean first
    to deploy it to the container, otherwise you will
    get an error!
  • As you make changes to your Entities, remember
    you will have to redeploy (make/rebuild, run) in
    order to have the changes take effect on the App
    Server.

31
It works! sort of -(
  • What does this mean?
  • com.rmoug.model.ExpertiseAreas_at_193c0cf

32
Refining the generated code
  • Need a way to query (and see) data
  • Need a way to make changes to data
  • Need a way to commit work

33
TopLink CRUD query methods Match Up Question
  • SQL TopLink
  • SELECT removeEntity()
  • INSERT queryEntityNameFindAll()
  • UPDATE persistEntity()
  • DELETE mergeEntity()

?
34
TopLink CRUD query operations Match Up Answer
  • SQL TopLink
  • SELECT removeEntity()
  • INSERT queryEntityNameFindAll()
  • UPDATE persistEntity()
  • DELETE mergeEntity()

35
TopLink CRUD query operations ANSWER
  • SQL TopLink
  • SELECT queryEntityNameFindAll()
  • INSERT persistEntity()
  • UPDATE mergeEntity()
  • DELETE removeEntityName()

36
Select All data query
  • Selecting data using the queryEntityNameFindAll()
    method
  • // Selects and prints out all rows
  • System.out.println("Products Query Result")
  • ListltProductsgt productsList sessionEJB.queryProd
    uctsFindAll()
  • for ( Products p productsList )
  • System.out.println( "Product ID "
    p.getProdId() )
  • System.out.println( "Product Name "
    p.getName() )
  • System.out.println( "Product Description "
  • p.getDescription() )
  • // end for
  • Well Build a named query with a where clause
    later in the session

37
Inserting Data using the persistEntity() method
  • // Inserts a row into the products table
  • Products p1 new Products()
  • p1.setName( IOUG Washing Machine" )
  • p1.setDescription( "Having fun at IOUG" )
  • sessionEJB.persistEntity( p1 )

38
Updating data using the mergeEntity() method
  • // Perform an update
  • // productsList.size() returns the size of the
    List
  • // Remember Java like C/C is zero based so we
    must
  • // subtract 1 to find the last element in the
    List
  • Products p2 new Products()
  • p2 productsList.get( productsList.size() - 1 )
  • p2.setName( IOUG iPod" )
  • p2.setDescription( "We updated this row!" )
  • sessionEJB.mergeEntity( p2 )

39
Delete data using the removeEntityName() method
  • // delete a Product from the List
  • Products p3 new Products()
  • p3 productsList.get( productsList.size() - 1 )
  • sessionEJB.removeProducts( p3 )

40
How do you find an Entity Row by Primary Key?
  • Need to create a new Named Query
  • Expose the new Query in the Session Bean
  • Test it out in the Client Test Harness

41
Find a row by primary Key Step 1. Create a
Named Query in Products.java EntityBean
  • Creating a new Named Query. If you have more
    than 1 query in a POJO, youll need to wrap the
    named queries in an _at_NamedQueries Annotation.
  • _at_NamedQueries(
  • _at_NamedQuery( name "Products.findAll",
  • query "select o from Products o" ) ,
  • _at_NamedQuery( name "Products.findByProdId",
  • query "select p from Products p where
  • p.prodId prodId")
  • )

Code that we added
42
Find a row by primary Key Step 2. Expose the
new method
  • Expose the findByProdId() method in the Session
    Bean

Right click on the SessionEJBBean.java file and
then Select Edit Session Façade
43
Find a row by primary Key Step 3.
  • Expose/Enable methods in the Session Façade
    wizard

Check the newly created Products.findByProdId
method. This will make it available to clients
at runtime.
44
Method generated for our new query in the session
bean
  • / ltcodegtselect p from Products p where p.prodId
    prodIdlt/codegt /
  • public ListltProductsgt queryProductsFindByProdId(
  • Object
    prodId )
  • return em.createNamedQuery( "Products.findByProd
    Id )
  • .setParameter( "prodId", prodId
    ).getResultList()
  • This cryptic little stub performs the following.
  • Accepts a prodId parameter.
  • Creates an instance of the findByProdId
    NamedQuery using the Entity Manager instance em.
  • Sets the required prodId parameter to the value
    passed to this method.
  • Returns a java.util.List object that contains all
    of the objects (rows) that satisfied this query
    by invoking the getResultList() method of the
    NamedQuery.

45
Test our new query in the EJB test client
  • System.out.println( "Products by Prod ID Query
    Result" )
  • ListltProductsgt productsList
  • sessionEJB.queryProductsFindByProdId( 100 )
  • for ( Products p productsList )
  • System.out.println( "Prod ID " p.getProdId()
    )
  • System.out.println( "Name " p.getName() )
  • System.out.println( "Description "
    p.getDescription() )

46
Database Transactions
  • What if I need a database transaction?
  • When we accepted the default settings, it set up
    the Entity objects to use Container Managed
    Persistence (CMP) and optimistic locking for row
    data.
  • This means that persistence operations will
    commit and rollback work automatically.
  • To get finer grained control youll need to
    review TopLinks transaction documentation in the
    Developers Guide.
  • TopLink provides support for commit, rollback and
    two-phase commit as expected.

47
Handling Schema Design Changes
  • Have a look at Offline Database Object
    Generation/Reconciliation.

48
Persistence Framework Issues
  • Very important to understand the relationship
    between your persistence framework and the
    database regarding synchronization.
  • Very important to implement and understand a
    synchronization strategy so that
    database/mid-tier consistency is maintained.

49
Recommendations
  • Use a persistence framework
  • Have a data architect role on project that works
    closely with the database administrator
    responsible for the schema administration.
  • Watch out for DML that is performed outside of
    the persistence framework
  • Get to know how to tune your persistence
    framework
  • Be on the lookout for rogue developers

50
Helpful information
  • EJB 3.0 TopLink Presentation Materials and Source
    Code
  • http//www.4shared.com/dir/5686418/9daee38b/RMOUG_
    2008.html
  • Oracle TopLink Homepage
  • www.oracle.com/technology/products/ias/toplink/ind
    ex.html
  • EJB 3.0 Resources
  • www.oracle.com/technology/tech/java/ejb30.html
  • Oracle JDeveloper Homepage
  • www.oracle.com/technology/products/jdev/index.html
  • EJB 3.0 Specification
  • java.sun.com/products/ejb/docs.html
  • TopLink Cache Invalidation
  • www.oracle.com/technology/products/ias/toplink/tec
    hnical/tips/DbChangeNotification/index.htm
  • Spy Mid-Tier SQL to Database
  • www.p6spy.com/

51
EJB 3.0 Java Persistence API (JPA) with Oracle
TopLink
  • Bill Lyons
  • Systems Architect
  • Hitachi Consulting
  • wlyons_at_hitachiconsulting.com
Write a Comment
User Comments (0)
About PowerShow.com