zawhtut
zawhtut

Reputation: 8541

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 ?

Upvotes: 4

Views: 12958

Answers (1)

Affe
Affe

Reputation: 47954

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
}

}

Upvotes: 6

Related Questions