简体   繁体   中英

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

In hibernate

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

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

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

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

@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
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM