InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

Java Persistence 2.0 Proposed Final Draft

Posted by Charles Humble on May 27, 2009

Sections
Architecture & Design,
Development,
Operations & Infrastructure
Topics
Java ,
Data Access
Tags
JPA

The Java Persistence API (JPA) version 2.0, now in proposed final draft, is a significant update to the specification adding an API for criteria queries, a metamodel API, and support for Bean Validation [JSR 303].

 The criteria query API allows the creation of queries by calling methods of Java objects, instead of by embedding JPA-QL into strings that are parsed by the JPA implementation. In the first public draft the API was itself string based and a lot of feedback was received by the expert group suggesting that they explore the possibility of improving the typesafety of the proposal. Gavin King responded with a suggestion which built upon the existing string based API and exploited the javax.annotation.Processor built into Java 6 to automatically generate a metamodel type for each persistent class in the application. Combined with generics, this mechanism provides an effective workaround for Java's lack of a typesafe metamodel for the methods and fields of a class. Whenever a code generator is used it is controversial since they have a tendency to produce code that is very difficult to follow and generally require specific IDE support. In this instance though, since the code is generated just for type information, it is possible to keep it fairly clean. For example, given a persistent class:

import java.util.Set;
import java.math.BigDecimal;
@Entity public class Order {
    @Id Integer orderId;
    @ManyToOne Customer customer;
    @OneToMany Set lineitems;
    Address shippingAddress;
    BigDecimal totalCost;
...
}

The corresponding canonical metamodel class, Order_, is as follows:

import java.math.BigDecimal;
import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.Set;
import javax.persistence.metamodel.TypeSafeMetamodel;
import javax.annotation.Generated;
@Generated
@TypeSafeMetamodel
public class Order_ {
    public static volatile Attribute<Order, Integer> orderId;
    public static volatile Attribute<Order, Customer> customer;
    public static volatile Set<Order, Item> lineitems;
    public static volatile Attribute<Order, Address> shippingAddress;
    public static volatile Attribute<Order, BigDecimal> totalCost;
}

 

Since the annotation processor is included with Java 6 the change also requires no specific IDE support – an IDE can delegate to the annotation processor triggered by the compiler and the metadata model is generated on the fly.

The metamodel can be queried via an API which specifies interfaces for dynamically accessing the metamodel of the persistent state and relationships of the managed classes of a persistence unit. It does not as yet offer support for accessing the object/relational mapping information though this is planned for a future update. The interfaces are implemented by the persistence provider and can be accessed through the methods EntityManagerFactory.getMetamodel and EntityManager.getMetamodel, which return the provider’s implementation class for the javax.persistence.metamodel.Metamodel interface.

King recently suggested a further refactoring that extends the typesafety through to the query resultset adding a type parameter to both CriteriaQuery and Query. This provides developers with direct access to typesafe lists of entities or wrappers but would result in compiler warnings for JPA 1.0 based projects since javax.persistence.Query does not currently have a type parameter.

The typesafe approach has been subject to some debate within the expert group. Writing on her blog, JPA 2.O specification lead Linda DeMichiel provides comparisons between the string and typesafe approaches and states that:

"After many discussions on the pluses and minuses of a metamodel-based API compared to a string-based API, we [the expert group] decided to adopt the typesafe API, but to provide developers the option of using a string-based approach if they prefer."

The main difference between the two options is that string based attribute names can be used as a means of specifying the attribute references in joins and navigation. The resulting queries have the same semantics as the typesafe version but without the same level of typesafety.

JPA 2.0 also defines support for the use of Bean Validation [JSR 303] within Java Persistence applications. Managed classes (entities, mapped superclasses and embeddable classes) may be configured to include Bean Validation constraints. Automatic validation using these constraints is achieved by specifying that Java Persistence applications delegate validation to the Bean Validation implementation upon the pre-persist, pre-update and pre-remove entity lifecycle events.

The expert group are keen to receive feedback from the community which can be sent to jsr-317-pfd-feedback@sun.com

criteria api by serge boulay Posted
The JPA Metamodel API has the potential to revolutionize Java development! by Jonas Bandi Posted
No thanks. by Ivan Lazarte Posted
Re: No thanks. by Andy Jefferson Posted
Re: No thanks. by William H Posted
Re: No thanks. by Gavin King Posted
  1. Back to top

    criteria api

    by serge boulay

    It will be be interesting to see what people think of the criteria api once the general public starts using it. I like the type safety aspect but am concerned that it will be at the expense of readability & verbosity.

  2. Back to top

    The JPA Metamodel API has the potential to revolutionize Java development!

    by Jonas Bandi

    The Ideas behind the new Metamodel API are astonishing and can be applied in other areas as well!
    I think this has the potential to revolutionize Java development!

    See my post on the topic: JPA2 - the potential to revolutionize Java development?

  3. Back to top

    No thanks.

    by Ivan Lazarte

    I really don't get stuff like this. While somewhat clever engineering-wise, to me, all it does is splinter the potential for a real type-safe method referencing inclusion later for Java. Why does the world revolve around a short-term enterprise mindset?

  4. Back to top

    Re: No thanks.

    by Andy Jefferson

    +1 to having a real type-safe Java language-based field/property reference process, rather than some "workaround" referring to some "internal" classes. Time would be much better spent there.

    --Andy (DataNucleus)

  5. Back to top

    Re: No thanks.

    by William H

    Funny - I see it exactly the opposite way. Had Java rushed to add support for method and field literals in the chances are that they would be how the JPA 2 criteria API was implemented but they wouldn't be enough to guarantee the typesafety that JPA 2 gives you. Its critical for JPA that the objects that represent attributes are parameterized also by the type they belong to. Having found a form of "DSL Support" that already exists in Java we can take a more measured, longer term view as to whether we need method and type literals or not. I think we do, btw, but I don't think they would have been the right choice here.

  6. Back to top

    Re: No thanks.

    by Gavin King

    Had Java rushed to add support for method and field literals in the chances are that they would be how the JPA 2 criteria API was implemented but they wouldn't be enough to guarantee the typesafety that JPA 2 gives you. Its critical for JPA that the objects that represent attributes are parameterized also by the type they belong to.


    Yes, that's right. A few people have missed the importance of this.

    The whole typesafety mechanism depends upon having the right generic declaration here:

    package javax.persistence.metamodel;

    /**
    * An attribute of a Java type
    *
    * @param <X> The represented type that contains the attribute
    * @param <Y> The type of the represented attribute
    */
    public interface Attribute<X, Y> { ... }
    </x,></y></x>

Educational Content

New-age Transactional Systems - Not Your Grandpa's OLTP

John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.

Cool Code

Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.