JPA vs Hibernate

As already everyone of you know, when you google “jpa vs hibernate” you find so much articles which of them are better. In our company we investigate which orm is better.

First at all, both ORMs now use xml mappings and annotations, deployer can override all of the properties, in jpa it is more convenient because all are do in one file. There are nearly the same. Going further hibernate is strict JPA, and provides some more extensions.

What’s more in Hibernate

  • Hibernate has more primary key generators.
  • Hibernate is no depend on entity classes so is strict POJO
  • Hibernate has more control over cascade behavior with Cascade.DELETE_ORPHAN and others.
  • Indexed collections
  • Criteria for nice query building.
  • Hibernate is JPA with EntityManager subproject.
  • Optimistic Locking strategy (OptimisticLockType.VERSION, OptimisticLockType.NONE, OptimisticLockType.DIRTY, OptimisticLockType.ALL)
  • BatchSize annotation sets batch size
  • Immutable annotation allows do some optimizations.
  • Filters and Filter annotations to apply on data
  • Cache annotation to define cache strategy and region of the cache

And some more, you can find it in hibernate annotation project documentation.

What’s new in JPA 2.0

JPA 2.0 (JSR 317) will be part of Java EE 6 platform. Although JPA 1.0 is rather great success, other products has better functionality as we write before.

  • Orphan removal – In parent-child relationship there can be a situation when child has no parent. One reason can be that parent was removed, so then every child is also removed, another situation is when child pointer to parent becomes null than this child should be removed.
  • Ordered collections – New annotation will be added to manage such collections. @OrderedColumn will automatically do all the stuff
  • Access Model – We can change access by @Access annotation, so now we can override access type both FIELD and PROPERTY in every point of hierarchy.

Some strategies

  1. Common properties such as id, uuid, audit data, can be put in some kind of base entity and mapped as MappedSupperclass. If for some reasons you have to redefine property you can do it using AttributeOveride annotation.
  2. Another good point is to create base dao using generics and use it to common task such as getById.
  3. One more is about audit data, and fields such create_date, last_update etc. For this propose you can use base dao or interceptors. Both solution has it’s pons and cons. For simple expectations dao is better approach.

Summary

In my opinion the best option is to use JPA whenever it is enough. Decide what JPA implementation you will be using, and when JPa isn’t enough use this JPA extension.
Spring Framework (TopLinkDialect, OpenJpaDialect, HibernateJpaDialect) supports changing JPA providers but I think you will never switch between them.
And what do you think about it?

Regards
Pedro