TypedQuery in JPA 2

One of the new feature introduced in JPA 2.0 is using the TypedQuery interface for building the query. This can be used with the CriteriaBuilder in JPA 2. As the name itself specifies, the main purpose of using the TypedQuery would be to narrow the result type and eliminate the need for type casting after the result is returned. Prior to this feature, the Query interface returns the generic object which needs to be typecast to the specific instance. This will have lot of issues like ClassCastException at run time if there is mismatch in both the types. JPA 2.0 added TypedQuery and over-loaded methods of EntityManager that allow you to specify the query result type.

Lets look at the simple example for using the TypedQuery.

EntityManager entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Employee> queryEmployee = entityManager.createNamedQuery("employee.findByEmployee",
queryEmployee.setParameter("employee", "Anand");
Employee employee = queryEmployee.getSingleResult();



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.