JPA Native Query选择和转换对象 [英] JPA Native Query select and cast object
问题描述
我有一个Object Admin
,它扩展了 User
。默认情况下,两个对象都在我的Derby数据库的表 User _
中(包含来自 Admin
的字段)。通常我会选择用户
,如下所示:
I have got an Object Admin
which extends User
. By default both Objects are in the table User_
of my Derby Database (included fields from Admin
). Normally I'd select an User
like this:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root user= query.from(User.class);
Predicate predicateId = cb.equal(category.get("id"), id);
query.select(user).where(predicateId);
return em.createQuery(query).getSingleResult();
然而,由于我的查询的复杂性,我正在使用这样的本机查询:
However due to the complexity of my query I'm using a native query like this:
Query query = em.createNativeQuery("SELECT USER.* FROM USER_ AS USER WHERE ID = ?");
query.setParameter(1, id);
return (User) query.getSingleResult();
虽然这会抛出强制转换异常。我认为这是由于 Admin
中的任何字段。
Though this throws a cast exception. I figure this is due to any fields from Admin
.
我的问题是,如何选择用户
使用与第一个示例相同结果的本机查询(包括 @LOB
和<$ c $的相同值c> @ManyToOne (等等),因为JPQL查询会返回)?
My question is, how can I select a User
using a native query with an equal result as the first example (including the same values for @LOB
and @ManyToOne
(et cetera) as the JPQL query would return)?
推荐答案
你可能会想尝试以下方法之一:
You might want to try one of the following ways:
-
使用方法
createNativeQuery(sqlString,resultClass)
本机查询也可以使用
EntityManager.createNativeQuery()动态定义
API。
String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
Query query = em.createNativeQuery(sql, User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
使用注释 @NamedNativeQuery
本机查询是通过 @NamedNativeQuery
和定义的@NamedNativeQueries
annotations,或< named-native-query>
XML元素。
Using the annotation @NamedNativeQuery
Native queries are defined through the @NamedNativeQuery
and @NamedNativeQueries
annotations, or <named-native-query>
XML element.
@NamedNativeQuery(
name="complexQuery",
query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
resultClass=User.class
)
public class User { ... }
Query query = em.createNamedQuery("complexQuery", User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
您可以在优秀的开放式书籍中阅读更多内容 Java持久性 (可在 PDF )。
You can read more in the excellent open book Java Persistence (available in PDF).
───────
注意:关于 的使用getSingleResult()
,参见为什么你不应该在JPA中使用 getSingleResult()
。
这篇关于JPA Native Query选择和转换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!