TypedQuery equivalent for JPA 1.0

ⅰ亾dé卋堺 提交于 2020-01-16 03:23:54

问题


I am quite new to JPA and I am using Apress JPA2 text book to learn it. I was trying to do the first example from the book. This following line of code gives me an error:

TypedQuery query = em.createQuery("SELECT e FROM Employee e", Employee.class);

saying that TypedQuery cannot be resolved to a type. After struggling for sometime I realised that I am using JPA version 1 which does not contain TypedQuery but just Query interface.

My question is whether there is an equivalent statement in JPA version 1. Kindly help. Thanks in advance.


回答1:


As TypedQuery was introduced from JPA-2.0, have to go for Query interface.

1) Native query to map the result type for the query (loosing portability).

Query selectQuery = entityManager.createNativeQuery("SELECT
 e FROM Employee e", Employee.class);

2) Creating query & then explicitly casting it to the result type (more preferable).

Query selectQuery = entityManager.createQuery("SELECT e FROM Employee e")
List<Employee> employees = (List<Employee>)selectQuery.getResultList(); //Multiple Result
Employee employee = (Employee)selectQuery.getSingleResult(); //Single Result


来源:https://stackoverflow.com/questions/6119683/typedquery-equivalent-for-jpa-1-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!