Java JPA 本机查询以返回具有来自多个表的字段的实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19092763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA native query to return the entity with fields from multiple tables
提问by Giovane
I have a query in JPA NativeSql, where I do "unions" of tables and joins. 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 NativeSql 中有一个查询,我在其中执行表和联接的“联合”。我用来自多个表的所有查询字段创建了一个实体。所以我不能像往常一样用 JPA 做“@Column”“@table”。
How could I set the given values ??of the query to my entity?
如何将查询的给定值设置为我的实体?
回答by VWeber
IMHO using DAOs with JPA isn't a good idea. But have a look at the Criteria API. You can construct such queries like the one you described with the CriteriaBuilder.
恕我直言,将 DAO 与 JPA 一起使用并不是一个好主意。但是看看Criteria API。您可以像使用CriteriaBuilder描述的那样构建此类查询。
回答by SudoRahul
You can use the overloaded EntityManager#createNativeQuery(sql,resultClass)method for this.
您可以为此使用重载的EntityManager#createNativeQuery(sql,resultClass)方法。
回答by Masudul
JPA
native SQL
is same as generic SQL
. You can do union
operation same as SQL
query do. 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.
JPA
nativeSQL
与 generic 相同SQL
。您可以执行union
与SQL
查询相同的操作。但是,如果你想做到这一点的JPQL
,比你需要使用EclipseLink
,becasue JPQL
的JPA
不支持联盟行动。
回答by Kevin Bowersox
Why not put the NATIVE SQL into a view? 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.
为什么不将 NATIVE SQL 放入视图中?然后只需创建一个映射到视图的实体,就像将任何普通实体映射到表一样。唯一的区别是您不能基于视图插入、更新或删除实体。
回答by Pieter
You can map the columns returned by your native SQL query to your entity by using @SqlResultSetMapping
.
您可以使用 将本机 SQL 查询返回的列映射到您的实体@SqlResultSetMapping
。
示例:
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.
可以在此处找到更多示例。