JPA 本机查询选择和转换对象 [英] JPA Native Query select and cast object

查看:28
本文介绍了JPA 本机查询选择和转换对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展 User 的对象 Admin.默认情况下,两个对象都在我的 Derby 数据库的表 User_ 中(包括来自 Admin 的字段).通常我会像这样选择一个 User:

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.

我的问题是,如何使用与第一个示例相同结果的本机查询选择 User(包括 @LOB 的相同值)>@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 动态定义原生查询.

  • Using the method createNativeQuery(sqlString, resultClass)

    Native queries can also be defined dynamically using the 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 定义注释,或 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 Persistence中阅读更多内容(可在 PDF).

    You can read more in the excellent open book Java Persistence (available in PDF).

    ─────────
    注意:关于 getSingleResult() 的使用,请参见 为什么你不应该在 JPA 中使用 getSingleResult().

    这篇关于JPA 本机查询选择和转换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆