1 / 20

Persistence Models

Persistence Models. Margaret Smith. Overview. Java Data Objects (JDO) Enterprise Java Beans (EJB) 3.0 Demos and code. What is JDO?.

brad
Download Presentation

Persistence Models

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Persistence Models Margaret Smith

  2. Overview • Java Data Objects (JDO) • Enterprise Java Beans (EJB) 3.0 • Demos and code

  3. What is JDO? • The Java Data Objects (JDO) API is a standard interface-based Java model abstraction of persistence developed as Java Specification Request 12 (JSR 12) under the Java Community Process.

  4. What is EJB 3.0? • Enterprise Java Beans (EJB) 3.0 is a deep overhaul and simplification of the EJB specification. EJB 3.0's goals are to simplify development and focus more on writing plain old java objects (POJOs) rather than on complex EJB APIs. • JSR-220 of the Java Community Process.

  5. How are EJB and JDO related? Plain old Java objects (POJOs) and dependency injection Java EE or SE JDO EJB 3.0 Hibernate TopLink Other technologies…

  6. Earlier EJB Versions vs EJB 3.0 • Focus on plain Java classes • Strong emphasis on Java metadata annotations eliminates need for deployment descriptor • Annotations take the form of @[Something] and are used to express meta-data • Specification of programmatic defaults • Provides default database • Less transactional code

  7. Step 1: Design your domain/model classes as you would do normally Step 2: Define their persistence definition using Meta-Data Step 3: Compile your classes, and instrument them (using a JDO enhancer) Step 4: Generate the database tables where your classes are to be persisted Step 5: Write your code to persist your objects within the DAO layer Step 6: Run your application Step 1: Design your domain/model classes as you would do normally Step 2: Define their persistence definition using annotations as Meta-Data Step 3: Compile your classes Step 4: Run your application Optional step: specify a database other than the default Hsqldb database Creating an application The JDO Process The EJB 3.0 Process

  8. Usage Models JDO Model EJB 3.0 Model User interface input Server User interface input Server Enhanced POJOs AnnotatedPOJOs Database Driver Database Driver HSQLDB MySQL

  9. Store application where objects are Product and Book Plain java objects PersistenceManager object More error checking Investment calculator application where objects are Fund and EntityCalculator Plain annotated java objects EntityManager object Demos and code JDO EJB 3.0

  10. JDO: Schema file <?xml version="1.0"?> <!DOCTYPE jdo PUBLIC "-//Sun Microsystems, Inc.//DTD Java Data Objects Metadata 2.0//EN" "http://java.sun.com/dtd/jdo_2_0.dtd"> <jdo> <package name="org.jpox.tutorial"> <class name="Product" identity-type="datastore"> <inheritance strategy="new-table"/> <field name="name" persistence-modifier="persistent"> <column length="100" jdbc-type="VARCHAR"/> </field> <field name="description" persistence-modifier="persistent"> <column length="255" jdbc-type="VARCHAR"/> </field> <field name="price" persistence-modifier="persistent"/> </class> <class name="Book" identity-type="datastore" persistence-capable-superclass="org.jpox.tutorial.Product"> <inheritance strategy="new-table"/> <field name="author" persistence-modifier="persistent"> <column length="40" jdbc-type="VARCHAR"/> </field> <field name="isbn" persistence-modifier="persistent"> <column length="20" jdbc-type="CHAR"/> </field> <field name="publisher" persistence-modifier="persistent"> <column length="40" jdbc-type="VARCHAR"/> </field> </class> </package> </jdo>

  11. JDO: Persistence Manager private static PersistenceManager createPersistenceManager() throws IOException { Properties properties = new Properties(); InputStream is=Main.class.getClassLoader().getResourceAsStream("jpox.properties"); if (is == null) { throw new FileNotFoundException("Could not find jpox.properties file that defines the JPOX persistence setup."); } properties.load(is); PersistenceManagerFactory pmfactory = JDOHelper.getPersistenceManagerFactory(properties); PersistenceManager pm = pmfactory.getPersistenceManager(); return pm; }

  12. JDO: Database interaction …. PersistenceManager pm = createPersistenceManager(); // Persistence of a Product and a Book. Transaction tx=pm.currentTransaction(); try{ tx.begin(); Product product = new Product("Sony Discman","A standard discman from Sony",49.99); Book book = new Book("Lord of the Rings by Tolkien","The classic story",49.99,"JRR Tolkien", "12345678", "MyBooks Factory"); pm.makePersistent(product); pm.makePersistent(book); tx.commit(); System.out.println("Product and Book have been persisted"); } finally{ if (tx.isActive()) { tx.rollback(); } pm.close(); } ….

  13. EJB: Fund.java import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "fund") public class Fund implements Serializable { private int id; private String name; private double growthrate; public Fund () { } public Fund (String name, double growthrate) { this.name = name; this.growthrate = growthrate; } @Id @GeneratedValue public int getId () { return id; } public void setId (int id) { this.id = id; } EJB 3.0 requires a default constructor Denotes a primary key automatically generated by the server

  14. EJB: EntityCalculator.java import trail.entity.beans.*; import javax.ejb.*; import javax.persistence.*; import java.sql.Timestamp; import java.util.Collection; @Stateless public class EntityCalculator implements Calculator { @PersistenceContext // (unitName="cal") protected EntityManager em; public void addInvestor (String name, int start, int end) { Investor investor = new Investor (name, start, end); em.persist (investor); } public void addFund (String name, double growthrate) { Fund fund = new Fund (name, growthrate); em.persist (fund); } …..Continued next slide Identifies class as a stateless session bean Injects an EntityManager object Saves entity bean instance to database as a new row

  15. EJB: EntityCalculator.java Find and retrive entity bean by using entity name and entity id public double calculate (int fundId, int investorId, double saving) { Investor investor = em.find(Investor.class, Integer.valueOf(investorId)); Fund fund = em.find(Fund.class, Integer.valueOf(fundId)); int start = investor.getStartAge(); int end = investor.getEndAge(); double growthrate = fund.getGrowthrate(); double tmp = Math.pow(1. + growthrate / 12., 12. * (end - start) + 1); double result = saving * 12. * (tmp - 1) / growthrate; Timestamp ts = new Timestamp (System.currentTimeMillis()); TimedRecord rec = new TimedRecord (fund, investor, saving, result, ts); em.persist (rec); return result; } …Continued next slide

  16. EJB: EntityCalculator.java EJB QL statement; returns a collection of entity beans matched by query public Collection<Fund> getFunds () { return em.createQuery("from Fund f").getResultList(); } public Collection <Investor> getInvestors () { return em.createQuery("from Investor p").getResultList(); } public Collection <TimedRecord> getRecords () { return em.createQuery("from TimedRecord r order by r.ts desc").getResultList(); } }

  17. EJB: Client code private EntityCalculator cal = null; public void jspInit () { try { InitialContext ctx = new InitialContext(); cal = (EntityCalculator) ctx.lookup ("EJB3Trail/EntityCalculator/local"); } catch (Exception e) { e.printStackTrace (); } } public void service (Request req, Response rep) { // ... ... double res = cal.calculate(fund, investID, saving); } If the application is deployed in a EAR file, the default JNDI name is the EAR-FILE-BASE-NAME/EJB-CLASS-NAME/local for the stub for local interface; same for local and remote interfaces

  18. Conclusion • JDO • EJB 3.0 • Questions

  19. System Requirements • JDO Demo • JPOX: Java Persistent Objects • MySQL database • MySQL Connector/J database driver • EJB 3.0 Demo • EJB 3.0 Trailblazer from JBoss • JBoss 4.0.4+ • EJB 3.0 module from JBoss (may be downloaded together with JBoss 4.0.4)

  20. References • EJB/JDO Persistence FAQ. Sun Developer Network (SDN). Version 2h 23-Feb-05. http://java.sun.com/j2ee/persistence/faq.html • JBoss Trailblazers and Demo Applications. JBoss: The Professional Open Source Company.. EJB 3 Trailblazer. http://www.jboss.com/docs/trailblazer • JPOX-1-1.0-rc-1 Out Now. JPOX: Java Persistent Objects. http://www.jpox.org/index.jsp • JPOX – Tutorial. JPOX: Java Persistent Objects. http://www.jpox.org/docs/1_1/tutorials/tutorial.html • MySQL Connector/j. MySQL. http://www.mysql.com/products/connector/j/

More Related