Download An Introduction to the Java Data Objects (JDO) API

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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