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", Employee.class); queryEmployee.setParameter("employee", "Anand"); Employee employee = queryEmployee.getSingleResult();