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
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
An Introduction to
Java Data Objects
David Jordan
Object Identity, Inc.
www.objectidentity.com
David Jordan — An Introduction to Java Data Objects
Page 1
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Presentation Overview
JDO Standard
Defining your model
Class enhancement
Establish datastore connection and
transaction context
Access/manipulate persistent objects
Access via extents and queries
Compare JDO to alternatives
David Jordan — An Introduction to Java Data Objects
Page 2
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
What Is JDO?
Transparent persistence of Java object
models in transactional datastores
Became a standard in March 2002 via JCP
Uses Java data model and language
¾Your Java classes serve as data model
¾Navigate your data using references &
collections
¾Query using your Java model, Java operators
Objects are auto-mapped to/from database
Object cache managed automatically
David Jordan — An Introduction to Java Data Objects
Page 3
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
JDO Resources
On the Web
¾http://java.sun.com/products/jdo
¾http://access1.sun.com/jdo
¾http://www.jdocentral.com
In Print
¾Four JDO books now available
David Jordan — An Introduction to Java Data Objects
Page 4
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Just a Few of the JDO Vendors
Relational database
¾SolarMetric, Libelis, Hemisphere Tech, Object
Industries, Object Frontier, Exadel, SAP, Signsoft
Object database
¾FastObjects, ObjectDB, Versant,
Progress Software
Open source
¾JBossDO, Jarkarta OJB, Speedo, TJDO, XORM
David Jordan — An Introduction to Java Data Objects
Page 5
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Small Number of Interfaces
JDO API defined in package javax.jdo
Interfaces
¾PersistenceManagerFactory
¾PersistenceManager
¾Transaction
¾Extent
¾Query
¾InstanceCallbacks
Class: JDOHelper
David Jordan — An Introduction to Java Data Objects
Page 6
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
JDO Exception Hierarchy
java.lang.RuntimeException
¾JDOException
• JDOCanRetryException
9 JDODataStoreException
9 JDOUserException
JDOUnsupportedOptionException
• JDOFatalException
9 JDOFatalUserException
9 JDOFatalInternalException
9 JDOFatalDataStoreException
JDOOptimisticVerificationException
David Jordan — An Introduction to Java Data Objects
Page 7
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Defining Your JDO Model
JDO model based on
¾Application's Java object model
¾XML metadata
Don't use JDO-specific types
¾Specific standard Java types are supported
¾Persistent classes don't need to import any JDO
Source not required to persist a class
Classes to persist must be enhanced
Persistent classes must have null constructor
David Jordan — An Introduction to Java Data Objects
Page 8
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Class and Field Modifiers
All Java class and field modifiers supported
¾public, private, protected
¾abstract, synchronized, volatile
¾static, final, transient
Fields never stored in datastore
¾final
¾static
(values never change)
(only one instance per class)
Fields not stored by default
¾transient (can override in XML metadata)
David Jordan — An Introduction to Java Data Objects
Page 9
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Field Types
Primitives (boolean, byte, int, float …)
Wrappers (Boolean, Byte, Integer …)
java.lang:
String, Number, Object
java.util:
Date, Locale
java.math: BigInteger, BigDecimal
Persistent class references
Interface references
David Jordan — An Introduction to Java Data Objects
Page 10
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Collections
Required
¾Collection, Set, HashSet
Optional
¾arrays, Hashtable, Vector
¾TreeSet
¾List, LinkedList, ArrayList
¾Map, HashMap, TreeMap
Most of the optional collections are
supported by most of the vendors
David Jordan — An Introduction to Java Data Objects
Page 11
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Inheritance
Class inheritance is supported
Persistence of a class is independent
of its location in a class hierarchy
¾Persistent class can extend a transient class
¾Transient class can extend a persistent class
Polymorphic references are supported
Must declare class' nearest persistent base
class in the class hierarchy in the metadata
David Jordan — An Introduction to Java Data Objects
Page 12
Example Schema:
Company Database
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
1
Department
Person
department
address 1
Address
projects
*
Project
projects
*
employees *
*
members
Employee
manager
1
David Jordan — An Introduction to Java Data Objects
Page 13
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Person class
package company;
import java.util.Date;
public class Person {
private String
firstname;
private String
lastname;
private Address address;
private Date
birthdate;
protected Person() { } // must have null constructor
// other methods including get/set methods
}
David Jordan — An Introduction to Java Data Objects
Page 14
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Employee class
package company;
import java.util.*;
public class Employee
private long
private Date
private float
private Department
private Employee
private HashSet
extends Person {
empid;
hiredate;
weeklyhours;
department;
manager;
projects; //element: Project
// constructors and methods
}
David Jordan — An Introduction to Java Data Objects
Page 15
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Department class
package company;
import java.util.*;
public class Department {
private int
deptid;
private String deptname;
private HashSet employees; // element:Employee
private HashSet projects; // element:Project
public Department() { }
// other constructors and methods
}
David Jordan — An Introduction to Java Data Objects
Page 16
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
XML Metadata
JDO metadata is specified in XML file
Metadata needed to specify
¾Which classes are persistent
¾Persistence info not expressible in Java
¾Override default persistence behaviors
¾Enable vendor-specific features
Can be
¾Specified with a GUI or by hand
¾Generated by a tool
David Jordan — An Introduction to Java Data Objects
Page 17
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
XML Metadata for Example
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE jdo SYSTEM "jdo.dtd">
<jdo>
<package name="company">
<class name="Address" />
<class name="Person" />
<class name="Employee"
persistence-capable-superclass="company.Person">
<field name="projects">
<collection element-type="company.Project"/>
</field>
</class>
David Jordan — An Introduction to Java Data Objects
Page 18
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Metadata
(Continued)
<class name="Department">
<field name="employees">
<collection element-type="company.Employee" />
</field>
<field name="projects">
<collection element-type="company.Project" />
</field>
</class>
<class name="Project">
<field name="members" >
<collection element-type="company.Employee"/>
</field>
</class>
</package>
</jdo>
David Jordan — An Introduction to Java Data Objects
Page 19
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Object / Relational Mappings
Approaches
¾Java model: generate relational schema
¾Relational schema: generate object model
¾Define mapping between existing object model
and relational schema
OR mappings are vendor-specific in JDO 1.0
OR mappings typically placed in metadata
Java source not impacted by OR mappings
JDO 2.0 to standardize OR mappings
David Jordan — An Introduction to Java Data Objects
Page 20
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Example OR Mapping
<class name="Employee"
persistence-capable-superclass="company.Person">
<extension key="table" value="EmpTable"
vendor-name="X" />
<field name="manager">
<extension key="column" value="mgr"
vendor-name="X" />
</field>
</class>
David Jordan — An Introduction to Java Data Objects
Page 21
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Class Enhancement
Data/methods added to persistent classes
to support database transparency
Several approaches to enhancement
¾Hand-code necessary code enhancements
¾Code generated by tool at source level
¾Use enhancer, code added at class file level
Interface standardized between
PersistenceManager and persistent instances
Binary compatibility across JDO enhancers
David Jordan — An Introduction to Java Data Objects
Page 22
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Enhancer
Source file (Employee.java)
public class Employee {
...
}
JDO XML Metadata
<class name="Employee">
<field name="projects">
<collection elementtype="Project"/>
</field>
</class>
javac
Enhanced class
Employee.class
Enhancer
Employee.class
public class Employee
implements
PersistenceCapable {
…
}
David Jordan — An Introduction to Java Data Objects
Page 23
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
PersistenceManager (PM)
Primary JDO interface for managing objects
Provides methods to
¾Make instances persistent, makePersistent()
¾Delete instances, deletePersistent()
Manages a cache of objects in transaction
¾Manages their identity and lifecycle
¾One copy of a persistent instance in the cache
Manages single transaction context
Used to create Query instances
David Jordan — An Introduction to Java Data Objects
Page 24
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Acquire a PersistenceManager
JDOHelper
getPersistence
ManagerFactory
(Properties)
JNDI
javax.naming.
InitialContext
lookup(String)
Persistence
Manager
Factory
getPersistenceManager()
Persistence
Manager
David Jordan — An Introduction to Java Data Objects
Page 25
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Get PMF via Properties
Property file:
javax.jdo.PersistenceManagerFactoryClass=
com.sun.jdori.fostore.FOStorePMF
javax.jdo.option.ConnectionURL=fostore:database/fostore
javax.jdo.option.ConnectionUserName=dave
javax.jdo.option.ConnectionPassword=jdo4me
Necessary code:
PersistenceManagerFactory pmf = null;
InputStream propStream =
new FileInputStream("jdo.properties");
Properties props = new Properties();
props.load(propStream);
pmf = JDOHelper.getPersistenceManagerFactory(props);
David Jordan — An Introduction to Java Data Objects
Page 26
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Establish Transaction Context
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
tx.begin();
// put database transaction logic here
tx.commit(); // or rollback() to abort transaction
// possibly multiple transactions
pm.close();
David Jordan — An Introduction to Java Data Objects
Page 27
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Persistence of Instances
Explicit persistence
¾PersistenceManager methods:
• void makePersistent(Object o);
• void makePersistentAll(Object[] a);
• void makePersistentAll(Collection c);
Persistence-by-reachability
¾Transient instance of a persistent class
referenced by a persistent instance
becomes persistent at transaction commit
¾Can persist an entire object graph
David Jordan — An Introduction to Java Data Objects
Page 28
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Example of Persistence
Transaction tx = pm.currentTransaction();
tx.begin();
Department dev = new Department(1000, "Development");
pm.makePersistent(dev);
Address addr =
new Address("100 Elm Street", "Cary", "NC", "27513");
Employee emp = new Employee("John", "Doe", addr);
dev.addEmployee(emp);
addr = new Address("250 Walnut Street",
"Apex", "NC", 27514);
emp = new Employee("Bob", "Jones", addr);
dev.addEmployee(emp);
tx.commit();
David Jordan — An Introduction to Java Data Objects
Page 29
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Accessing Instances
Iterate an extent or issue a query
to access some initial objects
Application can access related instances
¾Simply navigate through a reference
¾Iterate on a collection of references
JDO runtime loads instances on demand
¾One copy of each instance per transaction
You can directly access and modify fields
David Jordan — An Introduction to Java Data Objects
Page 30
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Modifying Instances
You can directly modify a field
Modify references and collections to change
the relationships among objects
Instances modified are automatically
marked as updated
All modifications to instances and their
interrelationships are automatically
propagated to the database at commit
David Jordan — An Introduction to Java Data Objects
Page 31
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Using an Extent
Extent depts = pm.getExtent(Department.class, true);
Iterator iter = depts.iterator();
while( iter.hasNext() ){
Department d = (Department) iter.next();
System.out.print("Department " + d.getName() );
Set employees = d.getEmployees();
Iterator empIter = employees.iterator();
while( empIter.hasNext() ){
Employee e = (Employee) empIter.next();
System.out.print("\t");
System.out.print(e.getFirstName());
System.out.println(e.getLastName());
}
}
depts.close(iter);
David Jordan — An Introduction to Java Data Objects
Page 32
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
JDO Query Language (JDOQL)
Use Java object model identifiers in filter
Use Java expressions and operators
Apply a Boolean filter to a set of candidates
¾Extent
¾Collection
Candidates are of a particular class
¾Establishes a scope for names in the query
¾Use import statements to include other types
Instances that evaluate true are in the result
David Jordan — An Introduction to Java Data Objects
Page 33
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Parameters, Navigation, Order
Query instance created with one of several
PersistenceManager.newQuery()
Parameters used to provide run-time values
Can navigate through references/collections
¾Variables used to reference collection elements
Result can be ordered
¾Similar to SQL order by
David Jordan — An Introduction to Java Data Objects
Page 34
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Operators in Query Filter
Oper
Descr
Oper
Descr
Oper
Descr
&
Boolean logical
AND
+
Addition
==
Equal
!=
Not equal
&&
Conditional AND
+
String
concatenation
<
Less than
|
Boolean logical
OR
-
Subtraction,
sign inversion
<=
Less than
or equal
||
Conditional OR
*
Multiplication
/
Division
>
Greater than
!
Logical
complement
>=
Greater than
or equal
~
Unary bitwise
compliment
David Jordan — An Introduction to Java Data Objects
Page 35
© Copyright 2003, Object Identity, Inc.
Colorado Software Summit: October 26 – 31, 2003
Example Query
Retrieve all employees
in a department named "Development"
that work on a project whose
name starts with the word "Database"
:Employee
:Department
department
deptname == "Development"
:Project
:Employee
projects
:Employee
:Project
:Project
name.startsWith("Database")
David Jordan — An Introduction to Java Data Objects
Page 36
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Code for the Query
String filter =
"department.deptName == dname && " +
"projects.contains(proj) && " +
"proj.name.startsWith(pname)";
Extent emps = pm.getExtent(Employee.class, true);
Query query = pm.newQuery(emps, filter);
query.declareImports("import company.Project");
query.declareVariables("Project proj");
query.declareParameters("String dname, String pname");
query.setOrdering(
"lastname ascending, firstname ascending");
Collection result = (Collection)
query.execute("Development", "Database");
Iterator iter = result.iterator();
David Jordan — An Introduction to Java Data Objects
Page 37
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
JDO and JDBC
JDBC
1.
2.
3.
4.
Transaction support
Relational data model
SQL queries, but with DBMS-specific dialects
Targeted DBMSs: relational
JDO
1.
2.
3.
4.
Transaction support
Java object model
JDOQL language, standard language/syntax
Targeted DBMSs: relational, object, others
David Jordan — An Introduction to Java Data Objects
Page 38
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
The Real Question to Ask…
Do you want your application to manage
information as objects or tables?
Is SQL or Java more suited for your data?
If you want to use objects and leverage the
benefits of object oriented development …
¾You should seriously consider JDO
¾You can still use JDBC too
If you want tables & SQL functionality…
¾Use JDBC
David Jordan — An Introduction to Java Data Objects
Page 39
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Alternatives to JDO
Use a vendor's nonstandard, proprietary API
Implement your own OR mapping
¾Development costs are prohibitive, ~30-40%
¾Resulting framework has limited capabilities
¾Requires high-level of staff expertise
Use EJB Container Managed Persistence
¾EJB is much more complex than JDO
¾Lacks support for object features like inheritance
¾Entity Bean performance may be unacceptable
David Jordan — An Introduction to Java Data Objects
Page 40
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Benefits of JDO
Developer productivity benefits
¾Provides mapping between objects & database
¾Developers stay focused on the object model
¾Application manages objects, not tables
¾Don't need database & model mapping experts
Portability benefits
¾JDO provides binary compatibility across all
JDO implementations and supported databases
¾JDO Query language consistent across impls.
David Jordan — An Introduction to Java Data Objects
Page 41
Colorado Software Summit: October 26 – 31, 2003
© Copyright 2003, Object Identity, Inc.
Summary of JDO
Very natural API for Java developers
¾Data model is Java
¾Access and navigation using Java constructs
¾Query language uses Java model and operators
Lets developers to focus on the
design of their Java object models
¾Without imposing modeling design constraints
Small number of interfaces to learn
David Jordan — An Introduction to Java Data Objects
Page 42