Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Persistence Models
Margaret Smith
Overview
Java Data Objects (JDO)
Enterprise Java Beans (EJB) 3.0
Demos and code
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.
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.
How are EJB and JDO related?
Java EE or SE
JDO
EJB 3.0
Hibernate
TopLink
Other
technologies…
Plain old Java
objects
(POJOs) and
dependency
injection
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
Creating an application
The JDO 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
The EJB 3.0 Process
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
Usage Models
JDO Model
User
interface
input
Server
Enhanced
POJOs
EJB 3.0 Model
User
interface
input
Server
Annotated
POJOs
Database Driver
Database Driver
MySQL
HSQLDB
Demos and code
JDO
Store application where
objects are Product and
Book
Plain java objects
PersistenceManager
object
More error checking
EJB 3.0
Investment calculator
application where
objects are Fund and
EntityCalculator
Plain annotated java
objects
EntityManager object
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>
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;
}
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();
}
….
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
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
EJB: 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);
return result;
}
…Continued next slide
Find and
retrive entity
bean by
using entity
name and
entity id
EJB: EntityCalculator.java
public Collection<Fund> getFunds () {
return em.createQuery("from Fund f").getResultList();
}
public Collection <Investor> getInvestors () {
return em.createQuery("from Investor p").getResultList();
}
EJB QL
statement;
returns a
collection of
entity beans
matched by
query
public Collection <TimedRecord> getRecords () {
return em.createQuery("from TimedRecord r order by r.ts desc").getResultList();
}
}
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-FILEBASE-NAME/EJBCLASS-NAME/local
for the stub for local
interface; same for
local and remote
interfaces
Conclusion
JDO
EJB 3.0
Questions
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)
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/