Tuesday Jun 02, 2015

Stored Procedure Support in JPA 2.1/Java EE 7

If you want to start a contentious debate at work, you should try initiating a discussion on the pros and cons of database stored procedures. If you want the discussion to be particularly colorful make sure to include a few DBAs or database developers instead of simply Java application developers :-). One of the least contentious benefits of stored procedures is that they can provide a performance boost for cases that involve multiple complex queries and heavy data manipulation by reducing the number of network round trips to the database. Some of the main weak points for stored procedures include lack of portability, weaker tooling for development/testing/debugging, and increased database load. The last one is a particularly salient point in my view - databases are the most difficult part of the data center to scale horizontally and they are already heavily IO bound. Frivolously adding stored procedures to the mix can work to make the database CPU bound to boot.

Where JPA and more generally ORM tools stand on this debate is not a great mystery - prior to JPA 2.1 the specification did not add direct support for stored procedures. That being said it should be noted that major JPA implementations have long supported stored procedures and adding support for them has been a frequent enough request for the JPA specification. The good news is that JPA 2.1 and Java EE 7 adds standardized support for accessing stored procedures. Pau Kiat Wee does a nice job of demonstrating the new feature in a very brief code centric blog post. Note that his example is Java SE based so it's actually even easier in a Java EE 7 environment. The newly added stored procedure support is very similar to the way JPA handles native queries. One of the best explanations of the feature comes from specification lead Linda DeMichiel. Check out minute 4-7 in the short video below (if you are having trouble accessing the embedded video it is available here).

Another very good source for more examples of the new feature is the EcliseLink 2.5 JPA 2.1 notes. Enjoy and don't forget to share if these are useful resources.

Please note that any views expressed here are my own only and certainly does not reflect the position of Oracle as a company

Monday Mar 30, 2015

Free JPA 2.1 Cheat Sheet by Thorben Janssen

Cheat sheets can be very handy while quickly referring to a technology one uses on a daily basis, although they can be tough to read (and write!) if the technology is very extensive like JPA. Fortunately, the changes in JPA 2.1 are definitely small enough to fit on a cheat sheet. Note, just because the amount of changes are small definitely does not mean they are not important. In fact, most of the changes in JPA 2.1 have generated a good deal of interest in the community and are already proving to be well received. Very fortunately for us, Thorben Janssen has gone through the effort of putting together a 100% free cheat sheet on the changes in JPA 2.1. You can download it from his related excellent blog entry aptly titled JPA 2.1 - 12 Features Every Developer Should Know.

If you look around Thorben's blog you'll find that he is trying his best to craft it to be a valuable resource to the community, including a weekly Java newsletter. If you find the JPA 2.1 cheat sheet to be useful, please do spread the word and consider dropping a brief note of appreciation for Thorben's hard work.

Wednesday Feb 25, 2015

Unsynchronized Persistence Contexts in JPA 2.1/Java EE 7

One of the more obscure features introduced in JPA 2.1 and Java EE 7 is the unsynchronized persistence context. It's not too surprising that the community does not seem to discuss it much - it's really geared towards somewhat an edge case.

Prior to JPA 2.1, the entity manager is always synchronized with the database when a JTA transaction commits. This poses a challenge if you have a multi-step workflow (let's say in a stateful session bean/CDI conversation/JSF flow) where you want some data to be flushed to the database on transaction commit at a given stage of the workflow but not all - but you do eventually want to synchronize all changes at some other point in the workflow. Non-standard solutions like Seam and the Hibernate flush mode have been the answer in the past to get around this problem. This is now solved in JPA 2.1 via the unsynchronized persistence context. In an unsynchronized persistence context changes are not automatically flushed to the database on transaction commit. Rather, you explicitly join the transaction when you want changes synchronized.

Hantsy Bai does a decent job explaining this through code examples. By far the best explanation of the feature comes from specification lead Linda DeMichiel. Check out minute 11-14 in the short video below (if you are having trouble accessing the embedded video it is available here).

What do you think of the feature? Do you think it is useful or obscure? The JPA spec is the best place to get further details if this intrigues you.

Wednesday Jan 21, 2015

Better CDI Alignment in JPA 2.1/Java EE 7

A long standing open debate within the Domain-Driven Design (DDD) community is whether entities should be able to access application services (roughly business facades in J2EE patterns parlance) and repositories (roughly DAOs in J2EE patterns parlance). If we think it's OK for entities to access these parts of the application, it poses a problem in JPA and other mainstream data access technologies - how do you inject objects into an entity? The answer today in JPA is that you can't do that. There are good technical reasons why it's difficult to allow CDI injection directly into JPA entities - it becomes very difficult to figure out how to manage the entity life-cycle if it is managed by both the CDI and JPA runtimes at the same time.

So is there a solution to this problem? The good news in JPA 2.1 and Java EE 7 is that there is a clever workaround. While you can't use CDI injection in entities, entity listeners now fully support injection. If needed you can then pass in an appropriately scoped injected object (probably an application scoped bean) into the entity or anything else that you need from the entity listener. This is exactly the technique demonstrated by Hantsy Bai in explaining CDI support in JPA 2.1 entity listeners. Besides entity access to services and repositories, being able to use injection in entity listeners is generally very helpful for more complex cross-cutting concern like requirements at the JPA layer. Prior to JPA 2.1 both Apache CODI and Seam 3 enabled injection into JPA entity listeners.

If you happen to need a basic introduction to JPA entity listeners, Alexandre Gama has one of the best compact write-ups I've seen so far.

For the record, I do think accessing application services and repositories in entities violates the separation of concerns principle and should be done very sparingly :-).

Please note that any views expressed here are my own only and certainly does not reflect the position of Oracle as a company.

Monday Dec 01, 2014

Bulk Update/Delete using the Criteria API in JPA 2.1/Java EE 7

It has long been possible to do bulk updates and deletes using JPQL in JPA. Since JPQL is closely modeled after SQL, it has the key advantages that SQL does - namely that it is a very compact and powerful DSL for relational data manipulation. JPQL is also a natural transition mechanism to JPA for folks that have worked with SQL for a while (such as myself).

The big drawback for JPQL is that it is decoupled from the Java compiler and thus less type-safe/more error-prone. This weakness becomes particularly salient while needing to dynamically construct queries at runtime (with JPQL this basically turns into a lot of hard-to-read string manipulation) or with folks coming from a Java/OO background without much preexisting experience with SQL/RDBMS. For these reasons, the type-safe, Java centric Criteria Query API was added to JPA 2.0/Java EE 6.

In JPA 2.1/Java EE 7 the Criteria API has been moved even closer to JPQL with the addition of bulk update and delete capabilities (the Criteria API in JPA 2.0 supported queries which is by far still the primary use case for the API). Hantsy Bai has a very nice post demonstrating how bulk updates/deletes look like using the JPA 2.1 Criteria API.

For a more basic overview of the Criteria API itself, you should check out the official Java EE 7 tutorial.

Wednesday Aug 20, 2014

Using the Java SE 8 Date Time API with JPA 2.1

Most of you are hopefully aware of the new Date Time API included in Java SE 8. If you are not, you should check them out right now using the Java Tutorial Trail dedicated to the topic. It is a significantly leap forward in processing temporal data in Java. For those who already use Joda-Time the changes will look very familiar - very simplistically speaking the Java SE 8 feature is basically Joda-Time standardized.

Quite naturally you will likely want to use the new Date Time APIs in your JPA domain model to better represent temporal data. The problem is that JPA 2.1 will not support the new API out of the box. So what are you to do? Fortunately you can make use of fairly simple JPA 2.1 Type Converters to use the Date Time API in your JPA domain classes. Steven Gertiser shows you how to do it in an extremely well written blog entry. Besides explaining the problem and the solution the entry is actually very good for getting a better understanding of JPA 2.1 Type Converters as well. I think such a set of converters may be a good fit for Apache DeltaSpike as a Java EE 7 extension?

In case you are wondering about Java SE 8 support in the JPA specification itself, Nick Williams has already entered an excellent, well researched JIRA entry asking for such support in a future version of the JPA specification that's well worth looking at. Another possibility of course is for JPA providers to start supporting the Date Time API natively before anything is formalized in the specification. What do you think?

Tuesday Jun 10, 2014

Type Conversion in JPA 2.1

The Java Persistence 2.1 specification (JSR 338) adds support for various new features such as schema generation, stored procedure invocation, use of entity graphs in queries and find operations, unsynchronized persistence contexts, injection into entity listener classes, etc.

JPA 2.1 also add support for Type Conversion methods, sometime called Type Converter. This new facility let developers specify methods to convert between the entity attribute representation and the database representation for attributes of basic types.

For additional details on Type Conversion, you can check the JSR 338 Specification and its corresponding JPA 2.1 Javadocs. In addition, you can also check those 2 articles. The first article ('How to implement a Type Converter') gives a short overview on Type Conversion while the second article ('How to use a JPA Type Converter to encrypt your data') implements a simple use-case (encrypting data) to illustrate Type Conversion. Mission critical applications would probably rely on transparent database encryption facilities provided by the database but that's not the point here, this use-case is easy enough to illustrate JPA 2.1 Type Conversion.

Wednesday Mar 12, 2014

JPA 2.1 Entity Graphs

Entity Graphs are a very important but somewhat underrated enhancement in JPA 2.1/Java EE 7. The feature significantly improves the ability to load/fetch JPA data beyond the very coarse grained mechanism of traditional ORM lazy and eager loading. Applied correctly, entity graphs could significantly improve application performance in still a fairly elegant way. Hantsy Bai does an excellent job explaining the basics of JPA 2.1 entity graphs in a recent blog post. He demonstrates how to define an entity graph using annotations or programatically, using the entity graph in a simple query and the basic value proposition for entity graphs. Linda DeMichiel dedicated a good amount of time explaining entity graphs during her JavaOne 2013 talk on JPA 2.1 (video below).

The official Java EE 7 tutorial also has a pretty decent section on entity graphs. It is definitely worth your time to understand the feature well and apply it in your JPA applications.

Wednesday Nov 20, 2013

JPA 2.1 Type Converters

Somewhat surprisingly, JPA 2.1 appears to be one of the APIs that seems to get lost in the Java EE 7 buzz. Although it is a point release JPA 2.1 includes a fairly large number of very important changes such as schema generation, entity graphs, support for stored procedures, unsynchronized persistence contexts, entity converters, and much, much more. In a code driven post Thorben Janssen discusses one of these changes - entity converters. There's also the 20-minute JPA 2.1 presentation by specification lead Linda Demichiel on the GlassFish videos YouTube channel:

More recently, Linda presented a JavaOne 2013 technical session titled Java Persistence 2.1. Stay tuned to Parleys.com for video of the session to be posted.