JPA entity without underlying table

后端 未结 1 1717
小蘑菇
小蘑菇 2020-12-25 14:41

I want to create a class that can be mapped to a result extracted from the database using JPA native query. Is there a way to map an entity without an underlying table to th

相关标签:
1条回答
  • 2020-12-25 15:41

    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)})
            })
    
    0 讨论(0)
提交回复
热议问题