Comments
jcl wrote: Hi,thank you for this tutorial I'm interested on the first way to intregate Spring and EJB3. I have tried it in a example project buy it doesn't run. I'm searching since many time a solution,but nothing. I have posted on Spring forum,but no one seems can help me. I appreciate if you can help me.Thank you Antonio
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Portable Persistence Using the EJB 3.0 Java Persistence API
The time for standardizing persistent POJOs has come

Experience has taught us that it's not enough to simply have a persistence standard as part of an enterprise specification. It must be a standard that can solve people's problems and be useful to most of the applications that want to use it. While earlier versions of Enterprise JavaBeans (EJB) persistence met some of the needs, they were primarily focused on the distributed problem domain. It is now known, and has been proven by successful commercial products like Oracle TopLink and Open Source projects like JBoss Hibernate, that the objects to be persisted don't have to be anything more than simple Java objects. The proof was in the popularity of these Object-Relational Mapping (ORM) tools; most developers have tended to pick up and use these tools rather than adopt the Java 2 Enterprise Edition (J2EE) entity bean programming standard.

The problem was that even though ORM technology suited them, some corporate IT shops were somewhat uncomfortable with using proprietary APIs in their large-scale applications. They wanted and needed the flexibility and reduced risk that comes with standards-based development. The time for standardization of persistent POJOs (Plain Old Java Objects) had come and the EJB 3.0 Java Persistence API (JPA) was born. It was completed and released as part of Java Enterprise Edition 5 (Java EE 5) in May 2006. Now everybody who has been using a proprietary Java persistence product can develop to a standard set of APIs and benefit from the portability and common experience that standards bring to the table. In this article we will introduce you to a few parts of the JPA API and show how they can enable developers to write portable persistence applications. We will also highlight interesting portability pitfalls that could ensnare the unwary developer.

The Domain Model
The primary currency of the JPA is the entity, which is just a regular Java object that may be persisted to a relational database. Entities can be created, queried for, accessed, modified, and removed from the table or tables that contain the state and are uniquely identified by means of their persistent identity or primary key.

Note that entities are quite different from the entity beans of previous EJB versions. Entity beans were full-bodied components that contained built-in remoting, transactional and security logic inserted into container-generated sub-classes by the EJB container at deployment time. Entity beans were created and destined to be entity beans, and were not suited to be anything else. Conversely, entities are simple object classes that don't have to contain any JPA-specific code. A class may often be designated as an entity without even changing a line of code in it; however, if annotations are used, the developer can choose to add them to the code if he decides it's appropriate. The entity object model is completely agnostic not only to the vendor (called the persistence provider) but possibly even the fact that it's persistent. For example, a developer could take an existing non-persistent class called Flight and make it persistent simply by indicating that it's an entity through the use of an @Entity annotation in the class:

@Entity public class Flight { ... }

Or, the developer could leave the class entirely alone and just add an entity entry in a separate XML mapping file:

<entity class="Flight">
    ...
</entity>

Regardless of which approach is used, the Flight class will continue to function as either a non-persistent class or a persistence entity depending on how it's used. It may have DomesticFlight, InternationalFlight, or other classes that extend it, and these classes may be entities or non-entities, but regardless of the JPA implementation, the object model can be exactly the same. No additional constraints, such as having to implement an interface or extend a special super-class, are imposed on the Flight class by either the API or persistence vendor implementations of the API.

O-R Mapping Metadata
We just saw how either an annotation or XML can be used to designate a class as an entity. This is obviously just scratching the surface of the metadata that is available and that dictates how the entity can be used or mapped. There's a host of JPA metadata in both annotation and XML forms, and the fact that this metadata is defined by the specification is significant for portability.

The largest portion of metadata is typically applied to entities for purposes of object-relational mapping, or mapping the state in the entity to the tables and columns in the database. Until JPA came along every ORM tool had its own way of defining and storing the ORM information for the entities that were mapped to the database. The JPA specification defines specifically and exactly how the metadata should be formed for a group of entities or the entities that make up a persistence unit. For example, we can choose to mark up our Flight class using annotations to indicate how it's mapped to the database.

@Entity
public class Flight {
    @Id
    @Column(name="ID")
    int flightNumber;

    @Column(name="DEP_TIME")
    Timestamp departureTime;

    String dest;

    @OneToMany(mappedBy="flight")
    Collection<Passenger> passengerList;

    ...
}

The annotations denote how the Flight class is mapped to the database. The @Table annotation is used to indicate to which table the entity is mapped, but it's often not even required since a default table name will be applied in its absence. The default name that is used is the unqualified name of the class. In this case the table will be called FLIGHT. The attribute mappings show how the members of the Flight class correspond to the columns of the FLIGHT table. The @Id annotation indicates that flightNumber is the primary key attribute, and the accompanying @Column annotation shows that it maps to the primary key column ID in the FLIGHT table. Likewise, the @Column annotation on the departureTime attribute denotes that the departure time is stored in the "DEP_TIME" column. Since there's no annotation on the dest attribute, the column name is defaulted to the name of the attribute, or DEST. The passengerList attribute is annotated with an @OneToMany annotation, signifying that it's a one-to-many relationship and the name of the foreign key or join column in the database is specified by the Passenger.flight attribute mapping.

All of this mapping metadata is very convenient in that regardless of the JPA implementation runtime, the same annotation configuration will imply exactly the same OR mappings. Even the same default values will be used since the rules for defaulting are dictated by the specification.

The XML mapping file alternative is equally portable in that the same mapping file(s) can be used when running with any and every compliant JPA vendor. The mapping files may be used to increment or even override the mapping information stored in annotations, and because the overriding characteristics are defined to the level of entity attributes, they can be portably overridden. For example, if we had an XML mapping file that contained the following, it would cause the departure time and destination to be stored in the DEPT_TIME and DST columns, respectively.

<entity class="Flight">
   <attributes>
     <basic name="departureTime">
       <column name="DEPT_TIME"/>
     </basic>
     <basic name="dest">
       <column name="DST"/>
     </basic>
   </attributes>
</entity>

Persistence Unit Metadata
The other main type of metadata is the persistence unit metadata, or metadata that applies to an entire group or configuration of entities. This metadata is stored in a file called persistence.xml and includes the things that are normally defined for a given runtime environment. For example, although JPA can run in a Java SE environment it will typically be used in an application server. When running in Java EE the persistence provider will have to know which data source to use to connect to in order to retrieve and store entity data. The JNDI name of the data source can be specified in the persistence.xml file, and is portable as long as that data source is configured and present in the JNDI namespace of the server runtime being used.

A number of provider-specific properties can be included in the persistence.xml file. The properties are primarily for non-standard features, but they are specified in a standard way that lets different vendors use the same format. So while developers may need to specify a different property for each vendor, a given vendor will recognize the properties that apply to it but ignore those that it doesn't know about. As an example, if a developer wanted the logging level to be set to the level that included printing the generated SQL and he was running in either TopLink Essentials or Hibernate then he would have the following property section in his persistence.xml file:

<properties>
    <property name="toplink.logging.level" value="FINE"/>
    <property name="hibernate.show-sql" value="true"/>
</properties>

Spring 2.0 users can make use of the additional Spring abstractions over some of the more common properties, such as logging, thereby gaining an additional level of portability across vendors.


About Mike Keith
Mike Keith has more than 15 years of teaching, research and practical experience in object-oriented and distributed systems, specializing in object persistence. He was the co-specification lead for EJB 3.0 (JSR 220), a member of the Java EE 5 expert group (JSR 244) and co-authored the premier JPA reference book Pro EJB 3: Java Persistence API. Mike is currently a persistence architect for Oracle and a popular speaker at numerous conferences and events around the world.

About Merrick Schincariol
Merrick Schincariol is a senior engineer for the Oracle OC4J Java EE Container. He was a lead engineer for Oracle's EJB 3.0 release and co-author of Pro EJB 3: Java Persistence API. Before joining Oracle, Merrick developed enterprise and large-scale systems for the telecomunications industry.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Enterprise Open Source Magazine Latest Stories . . .
About 10 years ago, a quiet bunch of IT revolutionaries, tired of expensive, complicated operating systems and the resources needed to support them, created a new breed of network management software and network monitoring systems. Pioneers like Solarwinds, Groundwork, Zoho (Adventnet)...
These days the popularity of Ext JS (a JavaScript library) is gaining momentum. One of the most popular widgets within Ext JS is the DataGrid. The reason – displaying data from a database is one of the most common tasks of a web application. “Out of the box” the DataGrid has functional...
PrismTech is joining forces with Nextel Engineering Systems to deliver much-needed, highly-reliable and Real-Time data management solutions. As part of its software and services offerings, Nextel Engineering will now deliver and support PrismTech’s best-in-class suite of middleware pro...
WS-BPEL 2.0 is the dominant specification to standardize orchestration logic and process automation between Web services. The BPEL model is used to assemble a set of discrete, essentially disparate, services into an end-to-end process flow to transform the existing stateless and uncorr...
Cloud computing is a game changer. The cloud is disrupting traditional software and hardware business models by disrupting how IT service gets delivered. Entrepreneurial opportunities abound as this classic disruptive technology begins to proliferate, so it is no surprise that SYS-CON'...
The newest release of Open-Xchange builds on a consistent theme as its delivers more integration with other webmail programs like Gmail, as well as the ability to incorporate contact information – the latest includes the Yahoo address book. Open-Xchange today announced enhancements tha...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE