java 使用 JPA 选择非实体?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2873902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:14:23  来源:igfitidea点击:

Select non-entities with JPA?

javajpa

提问by Redfield

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?
I have a non-entity class that wraps two entities:

JPA 是否可以使用本机查询检索非实体类的实例?
我有一个包装两个实体的非实体类:

class Wrap{
  Entity1 ent1;
  Entity2 ent2
}
@Entity
class Entity1{
  ...
}
@Entity
class Entity2{
  ...
}

How can I do something like that?

我怎么能做这样的事情?

Query q = entityManager.createNativeQuery("native select here");
List<Wrap> list = q.getResultList();

回答by Pascal Thivent

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?

JPA 是否可以使用本机查询检索非实体类的实例?

No. Native queries can return entities only(if you tell them to do so by passing the resultClassor a resultSetMappingto the createNativeQuerymethod; if you don't, you will get collections of raw data).

号机查询可以返回实体(如果你告诉他们通过将这样做,resultClass或者resultSetMappingcreateNativeQuery方法;如果你不这样做,你会得到原始数据的集合)。

In JPQL, you can use constructor expressions (SELECT NEW...) whith a non-entity constructor. But this is not supported for native queries, you'll have to do it manually.

在 JPQL 中,您可以使用带有非实体构造函数的构造函数表达式 (SELECT NEW...)。但是本机查询不支持此操作,您必须手动执行此操作。

回答by Lakshmi Hari

I think I found the solution. There is a way to use the NEW keyword in constructing the query. What I did to resovle this issue :

我想我找到了解决方案。有一种方法可以在构造查询时使用 NEW 关键字。我做了什么来解决这个问题:

    public List<ProductType> getProductByName(String productName) {
        String sqlQuery = "select DISTINCT **NEW** project1.ProductType(o.name, o.revision) from Lhproduct o where o.name = :prodname";
        Query qry = getEntityManager().**createQuery(sqlQuery);**
        qry.setParameter("prodname",productName);
        return qry.getResultList();
 }

The ProductType is a non-entity object, a simple plain object implementing Serialiabale. But you need to define the appropriate constructor.

ProductType 是一个非实体对象,一个简单的实现了Serialiabale 的普通对象。但是您需要定义适当的构造函数。

Happy coding :-)

快乐编码:-)

Thanks and Regards, Hari

谢谢和问候,哈里