java 如何将连接查询映射到 JPA 中的非实体类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5024533/
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-30 09:06:30  来源:igfitidea点击:

How to map join query to non-entity class in JPA?

javahibernatejpa

提问by zawhtut

In hibernate

处于休眠状态

Join queries can be mapped with non-entity class . How to map a database query into an Object [in Java]?

连接查询可以映射到非实体类。如何将数据库查询映射到对象 [在 Java 中]?

<class name=... select="select A.field_a, B.field_b, ... from A, B, ...">

How can I achieve the same thing in JPA/Hibernate ?

我怎样才能在 JPA/Hibernate 中实现同样的事情?

回答by Affe

In hibernate you can invoke a constructor of any arbitrary class inside the select clause of a query.

在休眠中,您可以在查询的 select 子句中调用任意类的构造函数。

@NamedQuery( name = "myScalarQuery" query =
"select new org.stackoverflow.hibernate.QueryResultObject(A.field_a, B.field_b) 
  from A, B
  where a.someUsefulProperty = b.someComparableProperty")

etc. (note fully qualified classname is required)

等(注意需要完全限定的类名)

Then you just need the class the has a matching constructor

然后你只需要具有匹配构造函数的类

public class QueryResultObject {

public QueryResultObject(TypeOfFieldA fieldA, TypeOfFieldB fieldB) {
//etc
}

}