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.
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
.
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.
You can use the overloaded EntityManager#createNativeQuery(sql,resultClass) method for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With