JPA 2.1 specification defines the means to return the result from a native query to a non entity class
You should checkout the heading 3.10.16.2 Returning Unmanaged Instances especially the
3.10.16.2.2 Constructor Results
The mapping to constructors is specified using the ConstructorResult
annotation element of the SqlResultSetMapping annotation. The
targetClass element of the ConstructorResult annotation specifies the
class whose constructor corresponds to the specified columns. All
columns corresponding to arguments of the intended constructor must be
specified using the columns element of the ConstructorResult
annotation in the same order as that of the argument list of the
constructor. Any entities returned as constructor results will be in
either the new or the detached state, depending on whether a primary
key is retrieved for the constructed object.
example
Query q = em.createNativeQuery(
"SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS
avgOrder" +
"FROM Customer c, Orders o " +
"WHERE o.cid = c.id " +
"GROUP BY c.id, c.name",
"CustomerDetailsResult");
@SqlResultSetMapping(name = "CustomerDetailsResult",
classes = {
@ConstructorResult(targetClass = com.acme.CustomerDetails.class,
columns = {
@ColumnResult(name = "id"),
@ColumnResult(name = "name"),
@ColumnResult(name = "orderCount"),
@ColumnResult(name = "avgOrder", type = Double.class)})
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…