Montag, 28. September 2009

JPA with Hibernate Criteria API

I didn't know that with JPA Vendor Hibernate, the Criteria API of Hibernate can be used. That can be done by getting the Hibernate Session from the JPA Entity Manager.

Here a example code:

Session session = (Session) entityManager.getDelegate();
Criteria hibernateCriteria = session.createCriteria(Position.class);
// List with all positions
List list = hibernateCriteria.list();

Ok the question is would you like to have a dependency to Hibernate in your source code when you would use JPA, I think you wold not like to have, but technical it works...

Nicer would be a Criteria API that depends only on JPA and is not JPA vendor specific. For JPA 1 I didn't know a project that provides such a Criteria API that works fine, but in JPA 2 I think the Crititeria API would be part of the standard, so I think thats a good news.

Another example:

// Implementation with Hibernate Criteria
public List getPositionList() {
Session session = (Session) entityManager.getDelegate();
Criteria hibernateCriteria = session.createCriteria(Position.class);
hibernateCriteria.addOrder(Order.desc("createTime"));
return hibernateCriteria.list();
}

// Implementation with plain JPA
public List getPositionList() {
Query query = entityManager.createQuery("SELECT p FROM Position p ORDER BY p.createTime DESC");
return query.getResultList();
}