JDO Technology Analysis and enterprise application research

Source: Internet
Author: User
Tags filter date array extend sql version variable tostring
JDO (Java Data Object) is an earlier developed and canonical JSR12 in JCP, which regulates the persistent storage of data and has many commercial products and open source projects based on this specification. As a kind of technology needing attention, it is very important to study and discuss the feasibility of the enterprise application.

   Preface

In enterprise-level application development, it is often necessary to have good persistence technology to support data storage. Through the good specification or the API, the Enterprise Domain business object carries on the persistent storage, mostly uses the O/R mapping technology to carry on the pattern Data transformation and the automatic mapping work.

JDO (Java Data Object) is an earlier developed and canonical JSR12 in JCP, which regulates the persistent storage of data and has many commercial products and open source projects based on this specification. As a kind of technology needing attention, it is very important to study and discuss the feasibility of the enterprise application.

The following is a brief introduction to the application development techniques for the JDO (JDO 1.0 specification) through this article, you can learn from the whole, and a more comprehensive understanding of JDO, master the main technical details and processes, understand its operating mechanism, and the enterprise-class application has a general grasp, which will help the enterprise application software technology selection, System architecture and analysis design activities.

This article is suitable for enterprise application architects, and concerned with data persistence layer design developers.

   JDO basic ideas and characteristics

An important problem of enterprise information system is to solve the data storage, that is, persistence. In the process of software development, the analyst analyzes the domain business, extracts the domain business model, and designs the database tables and corresponding fields that need to store the business data in the database.

And according to the business process, the design of business processing logic unit, data processing, processing and storage, inquiries and other services. One of the more annoying, boring job is to deal with a large number of data persistence code. To address the transformation of data from the business object layer to the data storage layer, JDO provides the corresponding development specification and API, solves the low-level processing process which is stored directly by Java object as the corresponding table of database, and helps designers to focus more on the higher level applications, such as business process and business object oriented.

The use of JDO mapping mechanism can reduce the coupling between business system and data storage system, it makes the business system portable in relation to relational database or object-oriented database, and the system is more lightweight, simpler and more maintainable because of the object-oriented (rather than the traditional) persistence technology.

   JDO Application examples and analysis

The following examples will be used to explain the JDO technology in a shallow and deep way.

   temporary objects and persistent objects

This is the code for an ordinary business object.

Package Business.model;
public class Book {
Private String ISBN;
private String name;
Private Date publishdate;
public void Setisbn (String ISBN) {
THIS.ISBN = ISBN;
}
Public String GETISBN () {
return THIS.ISBN;
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return this.name;
}
public void Setpublishdate (Date pubdate) {
This.publishdate = pubdate;
}
Public Date getpublishdate () {
return this.publishdate;
}
}
Now save it as an Jdo object in the database. The code is as follows:

Book book = new book ();
BOOK.SETISBN ("isbn-1234567");
Book.setname ("Java design pattern");

PersistenceManager manager = Persistencemanagerfactory.getpersistencemanager ();
Manager.currenttransaction (). Begin ();
Manager.makepersistence (book);
Manager.currenttransaction (). commit ();
The instance Book of the book class is a persistent object for the JDO API. Class book is a durable class. Is any ordinary Java Class A sustainable class of JDO? No. An object can be persisted to the database by JDO only if the following conditions are met.

The class to which it belongs should be marked as durable, with the following two methods:

Explicit: Implement interface, javax.jdo.PersistenceCapable can be;

Implicit: In the case of the Sun's JDO reference implementation, a BOOK.JDO file is required under the same path of the Book.java class.

<?xml version= "1.0" encoding = "UTF-8"?
! DOCTYPE jdo SYSTEM "JDO.DTD" >
<jdo>
<package name = "Business.model" >
<class name = "book"/>
</package>
</jdo>
and through the Bytecode enhancement tool (this example uses the Sun's bytecode enhancement tool) to process,

Javac Book.java
Java com.sun.jdori.enhancer.Main book.class book.jdo.


In both of these ways, the Book.class is a durable class.

Bytecode enhancements have the following features: When an application modifies a field by using the Set Method 1 o'clock, as a result of an enhanced procedure that inserts some code inside it, JDO obtains information about the change in the state of the data, thus making selective processing during the persistence process.

In accordance with the JDO specification, enhanced classes can be used on different JDO implementations without recompilation or enhancement.

Not all book objects are persistent objects, which are persistent objects only after makepersistence, and are stored in the database through the JDO implementation. By using the JDO Vendor extension tag (vendor-extension), you can describe in detail the storage characteristics of the book class, such as specifying database tables and corresponding fields for the durable class.

   Persistent Object Query

JDO queries are mainly in the following two ways.

• Use extend Query

Extend can query the persisted objects of the specified class and subclass.

PersistenceManager manager = Persistencemanagerfactory.getpersistencemanager ();
Manager.currenttransaction (). Begin ();
Extend Extend = Manager.getextend (book.class,true);//true indicates simultaneous querying of subclasses
Iterator it = Extend.iterator ();
while (It.hasnext ()) {
Book book = (book) it.next ();
System.out.println (BOOK.GETISBN ());
}
Extend.closeall ();
Manager.currenttransaction (). commit ();
The Extend Query method provides a class-based query that can form a more powerful query with query below.

• Query by using query

Query can specify a filter condition, which is a common way of querying.

The following example finds a book with the name "Start with Java design mode" and the publication date is less than today.

String filter = "((String) name). StartsWith (\" Java design mode \ ") && publishdate" Today ";
Query query = pm.getquery (Book.class,filter);
Query.declareimports ("Import java.util.Date");
Query.declareparameters ("Date Today");

Date today = new Date ();
Results = (Collection) query.execute (today);//Incoming parameter value
if (Results.isempty ()) {
System.out.println ("No data!");
}else{
Iterator it = Results.iterator ();
while (It.hasnext ()) {
Book book = (book) it.next ();
System.out.println ("book Name:" + book.getname () + ", ISBN:" + BOOK.GETISBN ());
}
}
Note: The condition uses a variable ' today ', declares the variable by "declareparameters", and passes in the instance of the variable in the "Execute" method.

This query with parameters is very similar to the way we used to use JDBC to query.

where StartsWith (string s) is the standard character method provided by Jdo, a similar method is EndsWith (string s).

JDOQL: The above use is a JDOQL sample, JDOQL is an integral part of the JDO specification. Using JDOQL, you can use applications to run on different JDO implementations. To address some of the deficiencies of JDOQL, the JDO specification provides support for specific JDO vendor query statement interfaces.

• Query sorting

The following example sorts the results of a query by "Publish Date Descending, title ascending".

Query query = pm.newquery (Book.class, filter);

String orderstr = "Publishdate decending, name ascending";
Query.setordering (ORDERSTR);

Results = Query.execute (today);
   Object Update

When the client updates the business data, it needs to be updated to the persistence layer through the business process.

There are two procedures that first locate the instance based on the primary key, then update the fields and submit. In the following example, the publication date of the book with the specified bibliography number is changed.

public void Updatebookpublishdate (String ISBN, Date newdate) {
PersistenceManager pm = null;
try{
PM = Pmf.getpersistencemanager ();
Object obj = pm.newobjectidinstance (BOOK.CLASS,ISBN);
Book book = (book) Pm.getobjectbyid (Obj,true);
Book.setpublishdate (newdate);
}catch (Exception e) {
Xxxcontext.setrollbackonly ();
throw new Exception (e);
}finally{
try{
if (PM!= null &&!pm.isclosed ()) {
Pm.close ();
}
}catch (Exception ex) {
System.out.println (ex);
}
}
Note, when PersistenceManager uses the Newobjectidinstance () method, how does jdo know to find the object by Book Number ISBN?

In fact, in the JDO description of this sustainable class book, you need to provide the following information:

<?xml version= "1.0" encoding = "UTF-8"?
! DOCTYPE jdo SYSTEM "JDO.DTD" >
<jdo>
<package name = "Business.model" >
<class name = "book" identity-type= "Application" objectid-class= "Bookkey"
<field name= "ISBN" primary-key= "true"/>
</class>
</package>
</jdo>
where "identity-type=" Application "" declares the persistent class book using the program identification method, that is, the Application incoming ID (field ISBN "Primary-key") information, JDO implementation constructs the specified "Objectid-class Instance (that is, the newobjectidinstance procedure), and JDO retrieves the specified persisted object (that is, Getobjectbyid).

Bookkey class source code is as follows:

Package Businesss.model;
public class Bookkey implements java.io.serializable{
Public String ISBN;
Public Bookkey () {}
Public Bookkey (String OID) {
ISBN = oid;
}
Public String toString () {
return ISBN;
}
Public Boolean equals (Object obj) {
Return Isbn.equals ((bookkey) obj). ISBN);
}
public int hashcode () {
return Isbn.hashcode ();
}
}
The "Objectid-class" category, such as "Bookkey", which complies with JDO, shall have the following conditions:

Class declared as public and implemented java.io.Serializable;

A construction method with a public and no parameters;

When a field is a primary key, it must be public, and the name and type are the same as the fields of the persisted class, for example: the Common String ISBN;

Equals and hashcode must use the primary key field value of all (especially the combined primary key of a multiple field);

A class must have a constructor method, and the process of the ToString method is a reverse process, the output value of the ToString is the input value of the constructor, and the instance can be regenerated (such as the constructor "public Bookkey (String oid)").

To sum up, if book is made up of two fields as primary keys, such as ISBN and name, the possible code is pm.newobjectidinstance (book.class,isbn+ "#" +name), and the Bookkey construction method is changed accordingly. And there are two public Fields "ISBN" and "name".

   Object Deletion

Object deletion takes the method deletepersistence. Examples are as follows:

Pm.currenttransaction (). Begin ();
Object obj = pm.newobjectidinstance (BOOK.CLASS,ISBN);
Book book = (book) Pm.getobjectbyid (Obj,true);
Pm.deletepersistence (book);
Pm.currenttransaction (). commit ();
   Get PersistenceManager Instance

All of the above operations are persistencemanager with the need for instance, which can be obtained under two environmental methods: non-regulated environment and managed environment.

• Non-regulated environment

The unmanaged environment is a two-tier development model, where the application directly obtains resource objects and carries out business operations. General transaction management, security management, or resource management require the application to maintain itself.

Properties Properties = new properties ();
Properties.put ("Javax.jdo.PersistenceManagerFactoryClass", "Com.xxx.jdo.xxxPMFClass");
Properties.put ("Javax.jdo.option.ConnectionURL", "xxx");
Properties.put ("Javax.jdo.option.ConnectionUserName", "xxx");
Properties.put ("Javax.jdo.option.ConnectionPassword", "xxx");
Persistencemanagerfactory PMF = Jdohelper.getpersistencemanagerfactory (properties);
PersistenceManager pm = Pmf.getpersistencemanager ();
Similar to the JDBC Fetch.

• Managed Environment

The managed environment is generally multi-layer development mode, especially in the Java EE application Environment, the program obtains resource object through the container, carries on the business operation, because in the container environment, the transaction, the security and the resource management all by the container carries on the unified centralized management, thus simplifies the code structure.

The following is an example of the code in the Setxxxcontext in EJB (Entitybean, Sessionbean, Messagedrivenbean).

Private Persistencemanagerfactory PMF;
public void Setxxxcontext (Xxxcontext context) {
try{
InitialContext CTX = new InitialContext ();
Object obj = ctx.lookup ("Java:compenvjdofactory");
PMF = (persistencemanagerfactory) portableremoteobject.narrow (O,persistencemanagerfactory.class);
}catch (Namingexception e) {
throw new Exception (e);
}
}
PMF is how to bind to the JNDI environment in Java, interested in reference to the JCA related technical documentation.

   Transaction Management

Business management and use, there are mainly the following three cases.

Bean management Scenarios with JDO transactions

Generally in the non-Java environment, the use of this transaction management model.

PersistenceManager pm = Pmf.getpersistencemanager ();
Pm.currenttransaction (). Begin ();
Do some business with JDO
Pm.currenttransaction (). commit ();
Pm.close ();
Bean management Scenarios with JTA transactions

Generally in the Java environment, in the case of bean-managed transactions, the following methods are used.

This approach can be used in EJB transaction environments.

Xxxcontext.getusertransaction (). Begin ();
PersistenceManager pm = Pmf.getpersistencemanager ();
Do some business with JDO
Xxxcontext.getusertransaction (). commit ();
Pm.close ();
• Container-managed scenarios using JTA transactions

Generally in the Java environment, the use of container management of the case, using the following methods.

The following is the business method for a session bean.

public void dobusiness () {
PersistenceManager pm;
try{
PM = Pmf.getpersistencemanager ();
Do some business with JDO
}catch (Exception e) {
Xxxcontext.setrollbackonly ();
System.out.println (e);
}finally{
try{
if (PM!= null &&!pm.isclosed ())
Pm.close ();
}catch (Exception ex) {
System.out.println (ex);
}
}
}
In summary, it can be concluded that the JDO operation is exactly the same as the JDBC operation.

   JDO Advanced Applications

• Persistence of Complex objects

In practical applications, a sustainable class is much more complex than the book class. It may reference other Java types, classes, collections, or arrays, and potentially complex inheritance relationships.

How does jdo perceive and track state changes when the state of these objects is changed?

JDO provides the appropriate APIs and specifications to implement this functionality.

• Basic types and references

The principle that the fields of a persistent class can be persisted by JDO implementations.

The original type, java.util.Date, etc. are supported (other more complex or optional features, as described in the JDO specification);

If the reference is a durable class, JDO is persisted;

A field declared by metadata (such as an JDO file) that is generally a reference to a non-persistent class and that jdo persists;

In the first two cases, JDO automatically senses when the state changes, but if the reference is a non-persistent class, it requires explicit notification by the code, or JDO does not store the changes. The following example:

public class Book {
......
private Object picture;
public void Setpicture (Object pic) {
Picture = pic;
}
Public Object getpicture () {
return to picture;
}
}
This class field picture needs to be persisted, but java.lang.Object is not a durable class, so it is declared as follows:

<?xml version= "1.0" encoding = "UTF-8"?
! DOCTYPE jdo SYSTEM "JDO.DTD" >
<jdo>
<package name = "Business.model" >
<class name = "book" >
<field name= "picture" persistence-modifier= "persistent"
</class>
</package>
</jdo>
If other modules get objects through Getpicture and modify objects outside of JDO's imperceptible exterior, the change is not stored, and a better approach is to modify the Setpicture method as follows:

public void Setpicture (Object pic) {
Jdohelper.makedirty (This, the "picture");
Picture = pic;
}
And the Setpicture method is used to update the data.

JDO's "makedirty" approach, which is primarily responsible for notifying the JDO implementation, changes the "Picture" field of an instance (this) of the persistent class book.

• Collection

When a field reference to a persistent class is set, the JDO specification enforces java.util.HashSet support for HashMap, HashTable, TreeMap, TreeSet, LinkedList, The support of ArrayList and vectors is optional for JDO implementations, and the implementation features are obtained through the Persistencemanagerfactory Supportedoptions method.

• array

If the reference to a durable class is an array type, when the array cell changes, you need to invoke "Makedirty" to notify the JDO implementation that the array reference content of the instance has changed.

Unlike a reference to a Non-persistent class instance, no JDO metadata declaration is required.

• Inheritance

If you use persistence, the generally inherited subclasses and parent classes are both persistent classes to reduce system complexity, and you need to indicate their persistent superclass in the metadata of the subclass, as follows:

<class name= "TechBook" persistence-capable-superclass= "book"/>
You can extend a persistent class for a non-persistent class, or you can extend a non-persistent class for a persistent class; Both scenarios the JDO implementation ignores the field portion of the Non-persistent class without saving it to the database.

   Some of the drawbacks of JDO

JDO is also deficient in the persistence of data compared to mature SQL, which in some cases may affect the design implementation of the data Processing section.

The following lists the essential features of common data access

• Query Enhancements

such as String does not support wildcard characters, case comparison;

Cannot implement Min, MAX, SUM, and AVG without support for aggregation operations;

The projection operation is not supported, and the JDO query returns as an object instead of returning fields like SQL;

does not support joint, cross (Union/intersect);

Join, in, and exists are not supported;

   Enterprise Application Research

Because JDO adopts object-oriented persistence processing technology, it provides a new technology solution to solve the problem of the persistence of enterprise business system. But the advanced may not be the most suitable. In some application scenarios, it is necessary to combine various factors and adopt flexible strategies.

• Object-oriented and record-oriented

Now most business systems adopt object-oriented analysis design, this requires each application system to map objects into records and store them in the database, and the object-oriented persistence technology such as JDO, to some extent, liberates the nonstandard nature of the transformation design and obtains the relatively better system structure. ; On the other hand, the data persistence of a business system generally has such a process: the object Layer-> record layer-> The physical layer, JDO undoubtedly makes the analysis designer free from the misery of the record layer, thus more focused on the object layer, which is an inspiring technology for the developers.

· JDO does not completely replace JDBC.

According to the classic "8-2 principle", if the use of JDO to solve the 80% problem, the remaining 20% by JDBC to achieve, this complementarity, each take the director's strategy, is a very effective way.

On the one hand, we can get better structure and improve the quality of development, on the other hand, to solve the jdo some of the technical deficiencies, and can be based on future technical changes, and then make appropriate transformation.

• Performance issues

There is no authoritative and satisfying answer to the better performance of JDO and JDBC. However, for some JDO implementations, the performance has been greatly improved by adopting the caching mechanism.

• Cross-database

JDO systems allow for better database porting and even running on object databases, and of course the JDBC processing layer, if fully compliant with the SQL-92 standard, also has a good cross database capability.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.