JPA Implementation Patterns

JPA implementation patterns: Wrap-up

Vincent Partington

The previous blog in the JPA implementation patterns series discussed different ways to test your JPA code. Figuring out how to test DAO’s and then being frustrated because the existing literature on JPA seemed to say very little on this subject, was actually the trigger for me to write these blogs. I have now come full circle, which means it’s time to wrap up the series. There’s lots more to write about, so keep following this blog! :-)

After discovering that there was a lack of documentation on how to use JPA in real-life scenario’s, I have written a series of blogs about the JPA implementation patterns I discovered while writing JPA code. To wrap up the series, I have made an overview of all the patterns that have been discussed for easy reference. The list is mostly in chronological order. I only changed the order slightly to make a distinction between the basic patterns and the advanced patterns.
 Read more

JPA implementation patterns: Wrap-up

Xebia Author

The previous blog in the JPA implementation patterns series discussed different ways to test your JPA code. Figuring out how to test DAO’s and then being frustrated because the existing literature on JPA seemed to say very little on this subject, was actually the trigger for me to write these blogs. I have now come full circle, which means it’s time to wrap up the series. There’s lots more to write about, so keep following this blog! :-)

After discovering that there was a lack of documentation on how to use JPA in real-life scenario’s, I have written a series of blogs about the JPA implementation patterns I discovered while writing JPA code. To wrap up the series, I have made an overview of all the patterns that have been discussed for easy reference. The list is mostly in chronological order. I only changed the order slightly to make a distinction between the basic patterns and the advanced patterns.
 Read more

JPA implementation patterns: Testing

Vincent Partington

In the previous blog in the JPA implementation patterns series, I talked about the three default ways of mapping inheritance hierarchies using JPA. And introduced one non-standard but quite useful method. This week I will discuss various approaches to testing JPA code.

What to test?

The first question to ask is: what code do we want to test? Two kinds of objects are involved when we talk about JPA: domain objects and data access objects (DAO’s). In theory your domain objects are not tied to JPA (they’re POJO’s, right?), so you can test their functionality without a JPA provider. Nothing interesting to discuss about that here. But in practice your domain objects will at least be annotated with JPA annotations and might also include some code to manage bidirectional associations (lazily), primary keys, or serialized objects. Now things are becoming more interesting…
 Read more

JPA implementation patterns: Mapping inheritance hierarchies

Vincent Partington

Last week I discussed the relative merits of field access versus property access in the ongoing JPA implementation patterns blog series. This week I will dwell on the choices offered when mapping inheritance hierarchies in JPA.

JPA provides three ways to map Java inheritance hierarchies to database tables:

  1. InheritanceType.SINGLE_TABLE – The whole inheritance hierarchy is mapped to one table. An object is stored in exactly one row in that table and the discriminator value stored in the discriminator column specifies the type of the object. Any fields not used in a superclass or a different branch of the hierarchy are set to NULL. This is the default inheritance mapping strategy used by JPA.
  2. InheritanceType.TABLE_PER_CLASS – Every concrete entity class in the hierarchy is mapped to a separate table. An object is stored in exactly one row in the specific table for its type. That specific table contains column for all the fields of the concrete class, including any inherited fields. This means that siblings in an inheritance hierarchy will each have their own copy of the fields they inherit from their superclass. A UNION of the separate tables is performed when querying on the superclass.
  3. InheritanceType.JOINED – Every class in the hierarchy is represented as a separate table, causing no field duplication to occur. An object is stored spread out over multiple tables; one row in each of the tables that make up its class inheritance hierarchy. The is-a relation between a subclass and its superclass is represented as a foreign key relation from the “subtable” to the “supertable” and the mapped tables are JOINed to load all the fields of an entity.

A nice comparison of the JPA inheritance mapping options with pictures, and including a description of the @MappedSuperclass option, can be found in the DataNucleus documentation.

Now the interesting question is: which method works best in what circumstances?
 Read more

JPA implementation patterns: Field access vs. property access

Vincent Partington

Last week my colleague Albert Sikkema blogged about using UUIDs as primary keys. Interesting stuff, thanks again, Albert! This week I will continue the JPA implementation patterns series by discussing the relative merits of field access vs. property access.

The JPA specification allows two ways for the persistence provider to access the persistent state of an entity. The persistence provider can either invoke JavaBeans style property accessors (getters and setters) or access the instance fields of the entity directly. Which method is used depends on whether you have annotated the properties or the fields of an entity.
 Read more

JPA implementation patterns: Using UUIDs as primary keys

Albert Sikkema

Continuing Vincent Partington‘s blog series about JPA implementation patterns, I would like to add the following

The default way in JPA for primary keys is to use the @GeneratedValue annotation with the strategy attribute set to one of AUTO, IDENTITY, SEQUENCE, or TABLE. You pick the most appropriate strategy for your situation and that’s it.
But you can also choose to generate the primary key yourself.
 Read more

JPA implementation patterns: Bidirectional associations vs. lazy loading

Vincent Partington

Two weeks ago I blogged about the use of the Service Facade and Data Transfer Object pattern in JPA application architecture. This week I will move from the high level perspective and discuss an interesting interaction I discovered between the way bidirectional associations are managed and lazy loading. So let’s roll up our sleeves and get dirty in this next installation of the JPA implementation patterns series. ;-)

This blog assumes that you are familiar with the Order/OrderLine example I introduced in the first two blogs of this series. If you are not, please review the example.

Consider the following code:

OrderLine orderLineToRemove = orderLineDao.findById(30);
orderLineToRemove.setOrder(null);

The intention of this code is to unassociate the OrderLine with the Order it was previously associated with. You might imagine doing this prior to removing the OrderLine object (although you can also use the @PreRemove annotation to have this done automatically) or when you want to attach the OrderLine to a different Order entity.

If you run this code you will find that the following entities will be loaded:

  1. The OrderLine with id 30.
  2. The Order associated with the OrderLine. This happens because the OrderLine.setOrder method invokes the Order.internalRemoveOrderLine method to remove the OrderLine from its parent Order object.
  3. All the other OrderLines that are associated with that Order! The Order.orderLines set is loaded when the OrderLine object with id 30 is removed from it.

 Read more

JPA implementation patterns: Service Facades and Data Transfers Objects

Vincent Partington

In my previous blog on JPA implementation patterns, I touched upon the subject of the DTO and Service Facade patterns. In this blog I will explore why we would even need such patterns and put these patterns and the DAO pattern into the broader context of JPA application architecture.

If there is one thing that I learned when implementing JPA for the first time is that some of the “old school” enterprise application architecture patterns still apply, even though some people have proclaimed them to be no longer necessary:

  • The DAO has been declared dead because you might just as well invoke the EntityManager directly. It provides a nice enough interface and switching from JPA to a different persistence implementation is not something the DAO abstraction would make much easier.
  • DTO’s have been deemed superfluous because you can also use your domain objects directly in the presentation layer. This is made possible by a combination of the open EntityManager in view pattern, tag libraries to display your domain objects in JSP’s and data-binding utilities to map HTTP request parameters back to domain objects.
  • And finally Service Facades also seem to have gone out of fashion. Instead you can have the controller directly invoke the services it needs or, even simpler, directly contain the business logic.

 Read more

JPA implementation patterns: Lazy loading

Vincent Partington

In the previous three blogs about JPA implementation patterns, I covered the basis operations of saving entities, retrieving entities, and removing entities. In this blog I will continue along a different angle, exploring the subject of how entities are lazily loaded and how that affects your application.

Anybody that has been working with Hibernate for a while has probably seen a LazyInitializationException or two, usually followed by a message such as “failed to lazily initialize a collection of role: com.xebia.jpaip.order.Order.orderLines, no session or session was closed” or “could not initialize proxy – no Session”. Even though these message may baffle new users of Hibernate, they are a lot better than the NullPointerExceptions OpenJPA gives you in these cases (at least when using runtime bytecode enhancement).

To use JPA to its full potential it is imperative to understand how lazy loading works, as it allows you to model your complete database with all its relations without loading that whole database as soon as you access just one entity.
 Read more

JPA implementation patterns: Removing entities

Vincent Partington

For the last few weeks I have been covering the implementation patterns I discovered while writing JPA applications. The last two blogs covered saving entities and retrieving entities. But when you’re really through with your entities, I guess you’d want to remove them too. ;-) So that is the subject of this blog.

Just like retrieving an entity, removing an entity is pretty simple. In fact it’s all you need to do is pass the entity to the EntityManager.remove method to remove the entity from the database when the transaction is committed (Of course you’d actually invoke a remove method on your DAO which in turn invokes EntityManager.remote). That’s all there is to it. Usually. Because when you’re using associations (be they bidirectional or not) things get more interesting.
 Read more