• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
EJB 3.0 Java Persistence with Oracle TopLink
 

EJB 3.0 Java Persistence with Oracle TopLink

on

  • 8,586 views

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

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

Statistics

Views

Total Views
8,586
Views on SlideShare
8,524
Embed Views
62

Actions

Likes
6
Downloads
268
Comments
1

5 Embeds 62

http://www.slideshare.net 38
http://www.e-presentations.us 17
http://www.linkedin.com 4
http://webcache.googleusercontent.com 2
https://www.linkedin.com 1

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1 previous next

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • what's this i couldnt able to download this presentation
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    EJB 3.0 Java Persistence with Oracle TopLink EJB 3.0 Java Persistence with Oracle TopLink Presentation Transcript

    • EJB 3.0 Java Persistence API JPA with Oracle TopLink Bill Lyons Systems Architect Huntsford Consulting [email_address]
    • 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 requery data from the database.
      • Caching improves performance, but it must be used appropriately.
    • 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.
    • J2EE Architecture Overview
    • J2EE Application Deployment View
    • Design separation in a typical web-based J2EE application
      • We’ll follow the Model-View-Controller OO Design Pattern:
      TopLink simplifies the development and maintenance of the ‘Model’ portion of an MVC application.
    • 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 as the data model changes.
      • JDBC code can be a significant source of performance and maintenance problems if not maintained properly.
      • Persistence frameworks are designed to improve performance while standardizing and simplifying development.
    • 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…
    • TopLink: recommended for new development efforts
      • Amongst Java developers it and Hibernate are the most widely used.
      • 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.
    • Demo Development/ Deployment Environment
      • Database
      • Oracle XE
      • Integrated Development Environment
      • Oracle JDeveloper 10.1.3.3
      • Application Server
      • Oracle 10g Application Server (OC4J) (embedded in JDeveloper for today’s demo)
      • Development Platform
      • Windows, Unix, Mac
    • TopLink Project Artifacts
      • A JDeveloper Database Connection
      • TopLink Plain old Java Objects (POJOs) that represent table metadata and table row instances
      • An EJB session bean that provides a way for 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.
    • TopLink Getting Started
      • Download and install database (or connect to an existing one)
      • Download and install JDeveloper 10.1.3.3
      • Build tables, indexes, sequences and constraints on the database: (We’ll use the Oracle SRDemo today as an example)
      • Install the SRDemo Tables, Indexes and Sequences. For the SRDemo, these are generated by running the build.sql script bundled with the application.
      • Be sure to get the SRDemo for TopLink – not ADF/BC or SRDemo for 4GL . There are different versions out there!
    • TopLink My First Persistence Tier
      • 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. (JDeveloper includes a small OC4J application server that we’ll use for local testing.)
      • Write a test client to test out the implementation.
    • SRDemo Schema
    • Setting up the Project
      • Start Database
      • Start JDeveloper
      • Create a Connection to the Database in JDeveloper
      • Create an Application and Workspace in JDeveloper
    • 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.
    • Create EJB 3.0 Entity Objects using TopLink
      • A TopLink Entity Object will be created for each table and view referenced.
      • Entity Objects provide an interface into a database tables
      • Entity Objects expose methods to operate on database columns.
      • Database views and synonyms are also viable selections for TopLink entities.
      • TopLink can reference database sequences or stored procedures to populate columns.
    • 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
    • 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.
    • Examining the Generated Java Source Code: for the ExpertiseAreas POJO
      • @Entity
      • @NamedQuery ( name = "ExpertiseAreas.findAll",
      • query = "select o from ExpertiseAreas o" )
      • @Table ( name = "EXPERTISE_AREAS" )
      • @IdClass ( ExpertiseAreasPK.class )
      • public class ExpertiseAreas implements Serializable {
      • @Column ( name="EXPERTISE_LEVEL", nullable = false )
      • private String expertiseLevel;
      • private String notes;
      • @Id
      • @Column ( name="PROD_ID", nullable = false, insertable = false, updatable = false )
      • private Long prodId;
      • @Id
      • @Column ( name="USER_ID", nullable = false, insertable = false, updatable = false )
      • private Long userId;
      • @ManyToOne
      • @JoinColumn ( name = "PROD_ID", referencedColumnName = "PROD_ID" )
      • private Products products;
    • 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;
      • }
      • public void setProdId( Long prodId ) {
      • this.prodId = prodId;
      • }
      • //… and so on…
    • 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.
    • Purpose of the Session Bean
      • 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.
      • Deployed with our POJOs to an EJB container.
    • Examining the Generated Source Code for the Session Bean
      • @Stateless ( name="SessionEJB" )
      • public class SessionEJBBean implements SessionEJB, SessionEJBLocal {
      • @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;
      • }
      • /** <code>select o from ExpertiseAreas o</code> */
      • public List<ExpertiseAreas> queryExpertiseAreasFindAll() {
      • return em.createNamedQuery(&quot;ExpertiseAreas.findAll&quot;).getResultList();
      • }
      • public void removeExpertiseAreas( ExpertiseAreas expertiseAreas ) {
      • expertiseAreas = em.find(ExpertiseAreas.class, new ExpertiseAreasPK(expertiseAreas.getProdId(), expertiseAreas.getUserId()));
      • em.remove(expertiseAreas);
      • }
    • 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…
    • 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(&quot;SessionEJB&quot;);
        • System.out.println( sessionEJB.queryExpertiseAreasFindAll( ) );
      • // 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();
      • }
      • }
    • 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.
    • It works! …sort of ;-(
      • What does this mean?
      • [email_address]
    • 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
    • TopLink CRUD query methods Match Up Question:
      • SQL TopLink
      • SELECT removeEntity()
      • INSERT query EntityName FindAll()
      • UPDATE persistEntity()
      • DELETE mergeEntity()
      ?
    • TopLink CRUD query operations: ANSWER
      • SQL TopLink
      • SELECT query EntityName FindAll()
      • INSERT persistEntity()
      • UPDATE mergeEntity()
      • DELETE remove EntityName ()
    • Select All data query
      • Selecting data using the query EntityName FindAll() method:
      • // Selects all rows from the Products table:
      • System.out.println(&quot;Products Query Result:&quot;);
      • List<Products> productsList = sessionEJB.queryProductsFindAll();
      • for ( Products p: productsList ) {
      • System.out.println( &quot;Product ID: &quot; + p.getProdId() );
      • System.out.println( &quot;Product Name: &quot; + p.getName() );
      • System.out.println( &quot;Product Description: &quot; +
      • p.getDescription() );
      • }// end for
    • Inserting Data using the persistEntity() method
      • // Insert a row into the products table:
      • Products p1 = new Products();
      • p1.setName( &quot;IOUG Washing Machine&quot; );
      • p1.setDescription( &quot;Having fun at IOUG&quot; );
      • sessionEJB. persistEntity ( p1 );
    • Updating data using the mergeEntity() method:
      • // Update a row in the products table:
      • // 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( &quot;IOUG iPod&quot; );
      • p2.setDescription( &quot;We updated this row!&quot; );
      • sessionEJB. mergeEntity ( p2 );
    • Delete data using the remove EntityName () method
      • // delete a Product from the Products table:
      • Products p3 = new Products();
      • p3 = productsList.get( productsList.size() - 1 );
      • sessionEJB. removeProducts ( p3 );
    • 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
    • Find a row by primary Key: Step 1. Create a Named Query in Products.java EntityBean
      • 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.
      • @ NamedQueries ({
      • @ NamedQuery ( name = &quot;Products.findAll&quot;,
      • query = &quot;select o from Products o&quot; ) ,
      • @ NamedQuery ( name = &quot;Products.findByProdId&quot;,
      • query = &quot;select p from Products p where
      • p.prodId = :prodId&quot;)
      • })
      Code that we added
    • 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…
    • 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.
    • Method generated for our new query in the session bean:
      • /** <code>select p from Products p where p.prodId = :prodId</code> */
      • public List<Products> queryProductsFindByProdId(
      • Object prodId ) {
      • return em.createNamedQuery( &quot;Products.findByProdId“ )
      • .setParameter( &quot;prodId&quot;, 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 prodId parameter to the value passed in to the 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.
    • Test our new query in the EJB test client
      • System.out.println( &quot;Products by Prod ID Query Result:&quot; );
      • List<Products> productsList =
      • sessionEJB. queryProductsFindByProdId ( 100 );
      • for ( Products p: productsList ) {
      • System.out.println( &quot;Prod ID: &quot; + p.getProdId() );
      • System.out.println( &quot;Name: &quot; + p.getName() );
      • System.out.println( &quot;Description: &quot; + p.getDescription() );
      • }
      • 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.
    • Handling Schema Design Changes
      • Have a look at Offline Database Object Generation/Reconciliation.
    • 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.
    • Recommendations
      • Use a persistence framework
      • Have a J2EE data architect role on project that works closely with the administrator responsible for database 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
    • Helpful information
      • EJB 3.0 TopLink Presentation Materials and Source Code
        • http://www.4shared.com/dir/6445050/5b75ff18/IOUG_2008.html
      • Oracle TopLink Homepage
        • www.oracle.com/technology/products/ias/toplink/index.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/technical/tips/DbChangeNotification/index.htm
      • Spy Mid-Tier SQL to Database
        • www.p6spy.com/
    • EJB 3.0 Java Persistence API (JPA) with Oracle TopLink Bill Lyons Systems Architect Huntsford Consulting [email_address]