Thursday, September 25, 2008

Retrieve EntityManager while using Spring JpaTemplate

In current project, I'm using Spring framework combine with OpenJpa. Life seems becoming much easier while using Spring JpaTemplate to handle all the database queries. However those methods provide by JpaTemplate class are not powerful enough to satisfy all kinds of requirements, so we may need use EntityManager to prepare query at some point.

When I was facing the problem of retrieve only the first n rows of a query, I could not find any method in JpaTemplate would that help me easily achieve this goal. At insult to the injury, there is no such keyword in JPQL like the rownum in Oracle or limit in Mysql that we can use directly into the query -- there may do have a keyword, but I didn't find by google. The only choice I have is to do it using Hibernate way, using setFirstResult() and setMaxResults() methods. In that case we do need an instance of EntityManager.

JpaTemplate class has a public method called getEntityManager(). The interesting fact is this mehod will always return null. Based on the online gossips of some people, though the getEntityManager's indentifier is public, no one should call it explicitedly. It can only be used by Spring itself. After further googled this issue, there are many ways to workaround this. Among all those solutions, using JpaCallback may be the simplest one.

There's some sample code:

List results = getJpaTemplate().executeFind(
new JpaCallBack() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(queryStr);
query.setFirstResult(0);
query.setMaxResults(1000);
List results = query.getResultList();
return results;
}
}
);

1 comment:

Sumedh said...

Thanks for this useful tip.