简体   繁体   English

JPA本机查询返回具有多个表的字段的实体

[英]JPA native query to return the entity with fields from multiple tables

I have a query in JPA NativeSql, where I do "unions" of tables and joins. 我在JPA NativeSql中有一个查询,在那里我做表和联接的“联合”。 I made an entity with all the query fields which are from multiple tables. 我创建了一个包含来自多个表的所有查询字段的实体。 So I can not do "@Column" "@ table" as usual with JPA. 所以我不能像往常一样用JPA做“@Column”“@ table”。

How could I set the given values ​​of the query to my entity? 如何将查询的给定值设置为我的实体?

You can map the columns returned by your native SQL query to your entity by using @SqlResultSetMapping . 您可以使用@SqlResultSetMapping将本机SQL查询返回的列映射到实体。

Example : 示例

Query q = em.createNativeQuery(
    "SELECT o.id AS order_id, " +
        "o.quantity AS order_quantity, " +
        "o.item AS order_item, " +
        "i.name AS item_name, " +
    "FROM Order o, Item i " +
    "WHERE (order_quantity > 25) AND (order_item = i.id)",
    "OrderResults");

@SqlResultSetMapping(name="OrderResults", 
    entities={ 
        @EntityResult(entityClass=com.acme.Order.class, fields={
            @FieldResult(name="id", column="order_id"),
            @FieldResult(name="quantity", column="order_quantity"), 
            @FieldResult(name="item", column="order_item")
        })
    },
    columns={
        @ColumnResult(name="item_name")}
)

More examples can be found here . 更多例子可以在这里找到。

IMHO using DAOs with JPA isn't a good idea. 恕我直言,使用DAO与JPA不是一个好主意。 But have a look at the Criteria API . 但是看看Criteria API You can construct such queries like the one you described with the CriteriaBuilder . 您可以构建类似于您使用CriteriaBuilder描述的查询。

JPA native SQL is same as generic SQL . JPA本机SQL与通用SQL相同。 You can do union operation same as SQL query do. 你可以像SQL查询那样进行union操作。 But, if you want to do it with JPQL , than you need to use EclipseLink , becasue JPQL of JPA does not support of Union operation. 但是,如果你想用JPQL做,那么你需要使用EclipseLink ,因为JPA JPQL不支持Union操作。

Why not put the NATIVE SQL into a view? 为什么不将NATIVE SQL放入视图中? Then just create an entity mapped to the view like any normal entity would be mapped to table. 然后只需创建映射到视图的实体,就像任何普通实体将映射到表一样。 The only difference being you cannot insert, update or delete entities based off of the view. 唯一的区别是您无法根据视图插入,更新或删除实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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