Title: Persistence Models
1Persistence Models
2Overview
- Java Data Objects (JDO)
- Enterprise Java Beans (EJB) 3.0
- Demos and code
3What 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.
4What 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.
5How 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
6Earlier 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 _at_Something and are
used to express meta-data - Specification of programmatic defaults
- Provides default database
- Less transactional code
7Creating an application
The JDO Process
The EJB 3.0 Process
- 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
8Usage Models
JDO Model
EJB 3.0 Model
User interface input
User interface input
Server
Server
Enhanced POJOs
AnnotatedPOJOs
Database Driver
Database Driver
HSQLDB
MySQL
9Demos and code
JDO
EJB 3.0
- 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
10JDO Schema file
- lt?xml version"1.0"?gt
- lt!DOCTYPE jdo PUBLIC
- "-//Sun Microsystems, Inc.//DTD Java Data
Objects Metadata 2.0//EN" - "http//java.sun.com/dtd/jdo_2_0.dtd"gt
- ltjdogt
- ltpackage name"org.jpox.tutorial"gt
- ltclass name"Product" identity-type"datas
tore"gt - ltinheritance strategy"new-table"/gt
- ltfield name"name" persistence-modifie
r"persistent"gt - ltcolumn length"100"
jdbc-type"VARCHAR"/gt - lt/fieldgt
- ltfield name"description"
persistence-modifier"persistent"gt - ltcolumn length"255"
jdbc-type"VARCHAR"/gt - lt/fieldgt
- ltfield name"price"
persistence-modifier"persistent"/gt - lt/classgt
- ltclass name"Book" identity-type"datastor
e"
11JDO Persistence Manager
- private static PersistenceManager
createPersistenceManager() throws IOException - Properties properties new Properties()
- InputStream isMain.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
-
12JDO Database interaction
- .
-
- PersistenceManager pm createPersistenceManager(
) - // Persistence of a Product and a Book.
- Transaction txpm.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())
-
13EJB Fund.java
- import javax.persistence.
- import java.io.Serializable
- _at_Entity
- _at_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
-
- _at_Id
- _at_GeneratedValue
EJB 3.0 requires a default constructor
Denotes a primary key automatically generated by
the server
14EJB EntityCalculator.java
- import trail.entity.beans.
- import javax.ejb.
- import javax.persistence.
- import java.sql.Timestamp
- import java.util.Collection
- _at_Stateless
- public class EntityCalculator implements
Calculator - _at_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)
Identifies class as a stateless session bean
Injects an EntityManager object
Saves entity bean instance to database as a new
row
15EJB EntityCalculator.java
- 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)
Find and retrive entity bean by using entity name
and entity id
16EJB EntityCalculator.java
EJB QL statement returns a collection of entity
beans matched by query
- public CollectionltFundgt getFunds ()
- return em.createQuery("from Fund
f").getResultList() -
- public Collection ltInvestorgt getInvestors ()
- return em.createQuery("from Investor
p").getResultList() -
- public Collection ltTimedRecordgt getRecords ()
- return em.createQuery("from TimedRecord r order
by r.ts desc").getResultList() -
-
17EJB 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-CL
ASS-NAME/local for the stub for local interface
same for local and remote interfaces
18Conclusion
19System 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)
20References
- EJB/JDO Persistence FAQ. Sun Developer Network
(SDN). Version 2h 23-Feb-05. http//java.sun.com/j
2ee/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.ht
ml - MySQL Connector/j. MySQL. http//www.mysql.com/pro
ducts/connector/j/