EJB 3.0 Java Persistence with Oracle TopLink


Published on

Getting started with Oracle TopLink and EJB 3.0 Java Persistence API JPA

Published in: Self Improvement, Technology
1 Comment
  • what's this i couldnt able to download this presentation
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

EJB 3.0 Java Persistence with Oracle TopLink

  1. 1. EJB 3.0 Java Persistence API JPA with Oracle TopLink Bill Lyons Systems Architect Huntsford Consulting [email_address]
  2. 2. Introduction <ul><li>Applications using a back end database and a web front end are the most common development architecture in use today. </li></ul><ul><li>Persistence frameworks provide a clean way to separate presentation logic and business logic from database operations. </li></ul><ul><li>Persistence frameworks help improve database performance through the use of a mid-tier cache. </li></ul><ul><li>The mid-tier improves user experience by caching frequently used data for recall without having to requery data from the database. </li></ul><ul><li>Caching improves performance, but it must be used appropriately. </li></ul>
  3. 3. Overview <ul><li>Examine the development of code that manages interaction between the database and applications. </li></ul><ul><li>Take a close look at TopLink - an Oracle owned persistence framework. </li></ul><ul><li>Discuss design tradeoffs and common issues associated with using a persistence tier. </li></ul>
  4. 4. J2EE Architecture Overview
  5. 5. J2EE Application Deployment View
  6. 6. Design separation in a typical web-based J2EE application <ul><li>We’ll follow the Model-View-Controller OO Design Pattern: </li></ul>TopLink simplifies the development and maintenance of the ‘Model’ portion of an MVC application.
  7. 7. The Persistence Management Problem <ul><li>Relational Databases and Object Oriented Languages organize data differently. </li></ul><ul><li>This makes it difficult for web developers to store and retrieve data from a database. </li></ul><ul><li>JDBC code provides access to the database, but is difficult to maintain as the data model changes. </li></ul><ul><li>JDBC code can be a significant source of performance and maintenance problems if not maintained properly. </li></ul><ul><li>Persistence frameworks are designed to improve performance while standardizing and simplifying development. </li></ul>
  8. 8. Competing Technologies that solve the persistence problem: <ul><li>Create your own connection pool and write JDBC and SQL code – ugly! </li></ul><ul><li>Use a persistence framework: </li></ul><ul><ul><li>Hibernate </li></ul></ul><ul><ul><li>Spring </li></ul></ul><ul><ul><li>JDO </li></ul></ul><ul><ul><li>BC4J </li></ul></ul><ul><ul><li>TopLink </li></ul></ul><ul><ul><li>… and many others… </li></ul></ul>
  9. 9. TopLink: recommended for new development efforts <ul><li>Amongst Java developers it and Hibernate are the most widely used. </li></ul><ul><li>Easy to use and maintain </li></ul><ul><li>Rich feature set </li></ul><ul><li>Easy for Java developers to learn: very well documented </li></ul><ul><li>Easy for DBAs to understand </li></ul><ul><li>Supported by Oracle </li></ul><ul><li>However , probably not appropriate for Oracle Apps integration. </li></ul><ul><li>Design Limitation/Recommendation: Use Only 1 persistence framework/strategy per database table. </li></ul>
  10. 10. Demo Development/ Deployment Environment <ul><li>Database </li></ul><ul><li>Oracle XE </li></ul><ul><li>Integrated Development Environment </li></ul><ul><li>Oracle JDeveloper </li></ul><ul><li>Application Server </li></ul><ul><li>Oracle 10g Application Server (OC4J) (embedded in JDeveloper for today’s demo) </li></ul><ul><li>Development Platform </li></ul><ul><li>Windows, Unix, Mac </li></ul>
  11. 11. TopLink Project Artifacts <ul><li>A JDeveloper Database Connection </li></ul><ul><li>TopLink Plain old Java Objects (POJOs) that represent table metadata and table row instances </li></ul><ul><li>An EJB session bean that provides a way for users to connect to the persistence tier and perform data operations. </li></ul><ul><li>Developer constructed queries. </li></ul><ul><li>Code to test out the persistence implementation using an EJB test client. </li></ul>
  12. 12. TopLink Getting Started <ul><li>Download and install database (or connect to an existing one) </li></ul><ul><li>Download and install JDeveloper </li></ul><ul><li>Build tables, indexes, sequences and constraints on the database: (We’ll use the Oracle SRDemo today as an example) </li></ul><ul><li>Install the SRDemo Tables, Indexes and Sequences. For the SRDemo, these are generated by running the build.sql script bundled with the application. </li></ul><ul><li>Be sure to get the SRDemo for TopLink – not ADF/BC or SRDemo for 4GL . There are different versions out there! </li></ul>
  13. 13. TopLink My First Persistence Tier <ul><li>Create a Connection from JDeveloper to the Database. </li></ul><ul><li>Create a new TopLink project and workspace in JDeveloper. </li></ul><ul><li>Run the TopLink wizard to create EJB 3.0 JPA Entity Objects and an EJB Session Bean. </li></ul><ul><li>Refine the design if necessary. </li></ul><ul><li>Deploy to an application server. (JDeveloper includes a small OC4J application server that we’ll use for local testing.) </li></ul><ul><li>Write a test client to test out the implementation. </li></ul>
  14. 14. SRDemo Schema
  15. 15. Setting up the Project <ul><li>Start Database </li></ul><ul><li>Start JDeveloper </li></ul><ul><li>Create a Connection to the Database in JDeveloper </li></ul><ul><li>Create an Application and Workspace in JDeveloper </li></ul>
  16. 16. 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 don’t use them in names or directory paths. Choose Web Application [JSF, EJB, TopLink] for the Application Template and click OK.
  17. 17. Create EJB 3.0 Entity Objects using TopLink <ul><li>A TopLink Entity Object will be created for each table and view referenced. </li></ul><ul><li>Entity Objects provide an interface into a database tables </li></ul><ul><li>Entity Objects expose methods to operate on database columns. </li></ul><ul><li>Database views and synonyms are also viable selections for TopLink entities. </li></ul><ul><li>TopLink can reference database sequences or stored procedures to populate columns. </li></ul>
  18. 18. 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
  19. 19. 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.
  20. 20. Examining the Generated Java Source Code: for the ExpertiseAreas POJO <ul><li>@Entity </li></ul><ul><li>@NamedQuery ( name = &quot;ExpertiseAreas.findAll&quot;, </li></ul><ul><li>query = &quot;select o from ExpertiseAreas o&quot; ) </li></ul><ul><li>@Table ( name = &quot;EXPERTISE_AREAS&quot; ) </li></ul><ul><li>@IdClass ( ExpertiseAreasPK.class ) </li></ul><ul><li>public class ExpertiseAreas implements Serializable { </li></ul><ul><li>@Column ( name=&quot;EXPERTISE_LEVEL&quot;, nullable = false ) </li></ul><ul><li>private String expertiseLevel; </li></ul><ul><li>private String notes; </li></ul><ul><li>@Id </li></ul><ul><li>@Column ( name=&quot;PROD_ID&quot;, nullable = false, insertable = false, updatable = false ) </li></ul><ul><li>private Long prodId; </li></ul><ul><li>@Id </li></ul><ul><li>@Column ( name=&quot;USER_ID&quot;, nullable = false, insertable = false, updatable = false ) </li></ul><ul><li>private Long userId; </li></ul><ul><li>@ManyToOne </li></ul><ul><li>@JoinColumn ( name = &quot;PROD_ID&quot;, referencedColumnName = &quot;PROD_ID&quot; ) </li></ul><ul><li>private Products products; </li></ul>
  21. 21. Examining the Generated Java Source Code: Column Code <ul><li>//… </li></ul><ul><li>public String getExpertiseLevel() { </li></ul><ul><li>return expertiseLevel; </li></ul><ul><li>} </li></ul><ul><li>public void setExpertiseLevel( String expertiseLevel ) { </li></ul><ul><li>this.expertiseLevel = expertiseLevel; </li></ul><ul><li>} </li></ul><ul><li>public String getNotes() { </li></ul><ul><li>return notes; </li></ul><ul><li>} </li></ul><ul><li>public void setNotes( String notes ) { </li></ul><ul><li>this.notes = notes; </li></ul><ul><li>} </li></ul><ul><li>public Long getProdId() { </li></ul><ul><li>return prodId; </li></ul><ul><li>} </li></ul><ul><li>public void setProdId( Long prodId ) { </li></ul><ul><li>this.prodId = prodId; </li></ul><ul><li>} </li></ul><ul><li>//… and so on… </li></ul>
  22. 22. 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.
  23. 23. Purpose of the Session Bean <ul><li>Encapsulates behavior needed by a client (could be web, swing client, or web service) so that the client can connect and query objects out of the persistence tier without having to know about database connections, SQL or database connectivity. </li></ul><ul><li>Deployed with our POJOs to an EJB container. </li></ul>
  24. 24. Examining the Generated Source Code for the Session Bean <ul><li>@Stateless ( name=&quot;SessionEJB&quot; ) </li></ul><ul><li>public class SessionEJBBean implements SessionEJB, SessionEJBLocal { </li></ul><ul><li>@PersistenceContext ( unitName=&quot;Model&quot; ) </li></ul><ul><li>private EntityManager em; </li></ul><ul><li>public Object mergeEntity ( Object entity ) { </li></ul><ul><li>return em.merge(entity); </li></ul><ul><li>} </li></ul><ul><li>public Object persistEntity ( Object entity ) { </li></ul><ul><li>em.persist(entity); </li></ul><ul><li>return entity; </li></ul><ul><li>} </li></ul><ul><li>/** <code>select o from ExpertiseAreas o</code> */ </li></ul><ul><li>public List<ExpertiseAreas> queryExpertiseAreasFindAll() { </li></ul><ul><li>return em.createNamedQuery(&quot;ExpertiseAreas.findAll&quot;).getResultList(); </li></ul><ul><li>} </li></ul><ul><li>public void removeExpertiseAreas( ExpertiseAreas expertiseAreas ) { </li></ul><ul><li>expertiseAreas = em.find(ExpertiseAreas.class, new ExpertiseAreasPK(expertiseAreas.getProdId(), expertiseAreas.getUserId())); </li></ul><ul><li>em.remove(expertiseAreas); </li></ul><ul><li>} </li></ul>
  25. 25. 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…
  26. 26. Examine the Generated Code for the Test EJB Client <ul><li>public class SessionEJBClient { </li></ul><ul><li>public static void main ( String [] args ) { </li></ul><ul><li>try { </li></ul><ul><li>final Context context = getInitialContext(); </li></ul><ul><li>SessionEJB sessionEJB = (SessionEJB)context.lookup(&quot;SessionEJB&quot;); </li></ul><ul><ul><li>System.out.println( sessionEJB.queryExpertiseAreasFindAll( ) ); </li></ul></ul><ul><li>// Call other methods of the Remote object to access the EJB </li></ul><ul><li>// sessionEJB.mergeEntity( expertiseAreas ); </li></ul><ul><li>// sessionEJB.persistEntity( expertiseAreas ); </li></ul><ul><li> // sessionEJB.removeExpertiseAreas( expertiseAreas ); </li></ul><ul><li>} </li></ul><ul><li>catch ( Exception ex ) { </li></ul><ul><li>ex.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  27. 27. Testing it all out <ul><li>Run the SessionEJBBean </li></ul><ul><ul><li>This deploys the SessionEJBBean, connection and Entity objects to the OC4J container embedded in JDeveloper. </li></ul></ul><ul><li>Run the SessionEJBClient </li></ul><ul><ul><li>The client will connect to the Web Application Server, locate the SessionEJBBean and execute methods on the remote session bean. </li></ul></ul><ul><li>Remember, you must run the SessionEJBBean first to deploy it to the container, otherwise you will get an error! </li></ul><ul><li>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. </li></ul>
  28. 28. It works! …sort of ;-( <ul><li>What does this mean? </li></ul><ul><li>[email_address] </li></ul>
  29. 29. Refining the generated code <ul><li>Need a way to query (and see) data </li></ul><ul><li>Need a way to make changes to data </li></ul><ul><li>Need a way to commit work </li></ul>
  30. 30. TopLink CRUD query methods Match Up Question: <ul><li>SQL TopLink </li></ul><ul><li>SELECT removeEntity() </li></ul><ul><li>INSERT query EntityName FindAll() </li></ul><ul><li>UPDATE persistEntity() </li></ul><ul><li>DELETE mergeEntity() </li></ul>?
  31. 31. TopLink CRUD query operations: ANSWER <ul><li>SQL TopLink </li></ul><ul><li>SELECT query EntityName FindAll() </li></ul><ul><li>INSERT persistEntity() </li></ul><ul><li>UPDATE mergeEntity() </li></ul><ul><li>DELETE remove EntityName () </li></ul>
  32. 32. Select All data query <ul><li>Selecting data using the query EntityName FindAll() method: </li></ul><ul><li>// Selects all rows from the Products table: </li></ul><ul><li>System.out.println(&quot;Products Query Result:&quot;); </li></ul><ul><li>List<Products> productsList = sessionEJB.queryProductsFindAll(); </li></ul><ul><li>for ( Products p: productsList ) { </li></ul><ul><li>System.out.println( &quot;Product ID: &quot; + p.getProdId() ); </li></ul><ul><li>System.out.println( &quot;Product Name: &quot; + p.getName() ); </li></ul><ul><li>System.out.println( &quot;Product Description: &quot; + </li></ul><ul><li>p.getDescription() ); </li></ul><ul><li>}// end for </li></ul>
  33. 33. Inserting Data using the persistEntity() method <ul><li>// Insert a row into the products table: </li></ul><ul><li>Products p1 = new Products(); </li></ul><ul><li>p1.setName( &quot;IOUG Washing Machine&quot; ); </li></ul><ul><li>p1.setDescription( &quot;Having fun at IOUG&quot; ); </li></ul><ul><li>sessionEJB. persistEntity ( p1 ); </li></ul>
  34. 34. Updating data using the mergeEntity() method: <ul><li>// Update a row in the products table: </li></ul><ul><li>// productsList.size() returns the size of the List </li></ul><ul><li>// Remember: Java like C/C++ is zero based so we must </li></ul><ul><li>// subtract 1 to find the last element in the List: </li></ul><ul><li>Products p2 = new Products(); </li></ul><ul><li>p2 = productsList.get( productsList. size() - 1 ); </li></ul><ul><li>p2.setName( &quot;IOUG iPod&quot; ); </li></ul><ul><li>p2.setDescription( &quot;We updated this row!&quot; ); </li></ul><ul><li>sessionEJB. mergeEntity ( p2 ); </li></ul>
  35. 35. Delete data using the remove EntityName () method <ul><li>// delete a Product from the Products table: </li></ul><ul><li>Products p3 = new Products(); </li></ul><ul><li>p3 = productsList.get( productsList.size() - 1 ); </li></ul><ul><li>sessionEJB. removeProducts ( p3 ); </li></ul>
  36. 36. How do you find an Entity Row by Primary Key? <ul><li>Need to create a new Named Query </li></ul><ul><li>Expose the new Query in the Session Bean </li></ul><ul><li>Test it out in the Client Test Harness </li></ul>
  37. 37. Find a row by primary Key: Step 1. Create a Named Query in Products.java EntityBean <ul><li>Create a new Named Query. If you have more than 1 query in a POJO, you’ll need to wrap the named queries in an @NamedQueries Annotation. </li></ul><ul><li>@ NamedQueries ({ </li></ul><ul><li>@ NamedQuery ( name = &quot;Products.findAll&quot;, </li></ul><ul><li>query = &quot;select o from Products o&quot; ) , </li></ul><ul><li>@ NamedQuery ( name = &quot;Products.findByProdId&quot;, </li></ul><ul><li>query = &quot;select p from Products p where </li></ul><ul><li>p.prodId = :prodId&quot;) </li></ul><ul><li>}) </li></ul>Code that we added
  38. 38. Find a row by primary Key: Step 2. Expose the new method <ul><li>Expose the findByProdId() method in the Session Bean: </li></ul>Right click on the SessionEJBBean.java file and then Select Edit Session Façade…
  39. 39. Find a row by primary Key: Step 3. <ul><li>Expose/Enable methods in the Session Façade wizard: </li></ul>Check the newly created Products.findByProdId method. This will make it available to clients at runtime.
  40. 40. Method generated for our new query in the session bean: <ul><li>/** <code>select p from Products p where p.prodId = :prodId</code> */ </li></ul><ul><li>public List<Products> queryProductsFindByProdId( </li></ul><ul><li>Object prodId ) { </li></ul><ul><li>return em.createNamedQuery( &quot;Products.findByProdId“ ) </li></ul><ul><li>.setParameter( &quot;prodId&quot;, prodId ).getResultList(); </li></ul><ul><li>} </li></ul><ul><li>This cryptic little stub performs the following. </li></ul><ul><li>Accepts a prodId parameter. </li></ul><ul><li>Creates an instance of the findByProdId NamedQuery using the Entity Manager instance em. </li></ul><ul><li>Sets the prodId parameter to the value passed in to the method. </li></ul><ul><li>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. </li></ul>
  41. 41. Test our new query in the EJB test client <ul><li>System.out.println( &quot;Products by Prod ID Query Result:&quot; ); </li></ul><ul><li>List<Products> productsList = </li></ul><ul><li>sessionEJB. queryProductsFindByProdId ( 100 ); </li></ul><ul><li>for ( Products p: productsList ) { </li></ul><ul><li>System.out.println( &quot;Prod ID: &quot; + p.getProdId() ); </li></ul><ul><li>System.out.println( &quot;Name: &quot; + p.getName() ); </li></ul><ul><li>System.out.println( &quot;Description: &quot; + p.getDescription() ); </li></ul><ul><li>} </li></ul><ul><li>Remember: Because we added a new named query to Products.java and a method to the Session Bean we’ll need to redeploy the application to the application server to get the changes to be published. </li></ul>
  42. 42. Handling Schema Design Changes <ul><li>Have a look at Offline Database Object Generation/Reconciliation. </li></ul>
  43. 43. Persistence Framework Issues <ul><li>Very important to understand the relationship between your persistence framework and the database regarding synchronization. </li></ul><ul><li>Very important to implement and understand a synchronization strategy so that database/mid-tier consistency is maintained. </li></ul>
  44. 44. Recommendations <ul><li>Use a persistence framework </li></ul><ul><li>Have a J2EE data architect role on project that works closely with the administrator responsible for database schema administration. </li></ul><ul><li>Watch out for DML that is performed outside of the persistence framework. </li></ul><ul><li>Get to know how to tune your persistence framework </li></ul><ul><li>Be on the lookout for rogue developers </li></ul>
  45. 45. Helpful information <ul><li>EJB 3.0 TopLink Presentation Materials and Source Code </li></ul><ul><ul><li>http://www.4shared.com/dir/6445050/5b75ff18/IOUG_2008.html </li></ul></ul><ul><li>Oracle TopLink Homepage </li></ul><ul><ul><li>www.oracle.com/technology/products/ias/toplink/index.html </li></ul></ul><ul><li>EJB 3.0 Resources </li></ul><ul><ul><li>www.oracle.com/technology/tech/java/ejb30.html </li></ul></ul><ul><li>Oracle JDeveloper Homepage </li></ul><ul><ul><li>www.oracle.com/technology/products/jdev/index.html </li></ul></ul><ul><li>EJB 3.0 Specification </li></ul><ul><ul><li>java.sun.com/products/ejb/docs.html </li></ul></ul><ul><li>TopLink Cache Invalidation </li></ul><ul><ul><li>www.oracle.com/technology/products/ias/toplink/technical/tips/DbChangeNotification/index.htm </li></ul></ul><ul><li>Spy Mid-Tier SQL to Database </li></ul><ul><ul><li>www.p6spy.com/ </li></ul></ul>
  46. 46. EJB 3.0 Java Persistence API (JPA) with Oracle TopLink Bill Lyons Systems Architect Huntsford Consulting [email_address]
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.