Hibernate and JPA APIs

Hibernate and JPA APIs - ** DRAFT**


It is obvious on inspection that JPA borrows a lot of its core ideas from Hibernate. Nontheless, with a decade of experience in Hibernate, the developers of JPA did not feel obliged to copy its API verbatim, but to develop a new one. In most cases the semantics of these methods are similar, but not always identical, so don't take this comparison too literally; understanding the details of the API is always a prerequisite for applying it successfully!

Overall Similarities
FunctionHibernate ClassJPA Class
Read config, create factoryConfigurationPersistence
Config file/hibernate.cfgMETA-INF/persistence.xml
Wrap Connection; CRUD methodsSessionEntityManager

Entity Classes and Mappings

You can use the same Java Annotations to mark up your entity classes and use them with either API, as long as you use the ones in javax.persistence. The annotations in org.hibernate.annotation should not be used except where they go beyond the JPA standard; they appear to be left over from a time when Hibernate planned to implement their own annotations to replace their somewhat cumbersome XML configuration.

CRUD Methods

The CRUD operations are methods of the Hibernate Session or the JPA EntityManager.

Recent versions of Hibernate have added many of the JPA EntityManager methods into the Session object, for further inter-operatility of code.

FunctionHibernate MethodJPA Method
Begin SessionsessionFactory.getSession()entityManagerFactory.getEntityManager();
Begin Local TransactionhibernateSession.beginTransaction()entityManager.getTransaction();
Commit Transactiontransaction.commit()transaction.commit()
Save New ObjecthibernateSession.save(entity)entityManager.persist(entity)
Find object by primary keyhibernateSession.get(entityClazz, pKey)entityManager.find(entityClazz, pkey)
Update object back to databasehibernateSession.update(entity)N/A; just update in a transaction
Refresh object from databaserefresh()refresh()

Query Language

The Query Languages are similar to each other and are based on an object-oriented abstraction of SQL. Both are case-insensitive for keywords (which are shown in upper case in the table) and case-sensitive for class and variable names.

Unfortunately, when using Hibernate as your JPA provider, you can use either form; this is unfortunate as it will make it harder to change providers later.

Query Language
FunctionHibernate QueryJPA Query
Select All FROM EntityClassSELECT entity FROM EntityClass entity;
Select w/ Where SELECT e FROM Entity e where e.property = value;
Select Indiv. fields SELECT e.title,e.price FROM Entity e;
Select & Create Transfer obj (Note 1) SELECT NEW VideoDTO(v.title,v.price) FROM Entity v

Note 1: Transfer object "VideoDTO" need not be a mapped entity, but must have the requisite public constructor for the arguments you are passing. If it is not a mapped class, you must use its fully-qualified class name.