Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

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?

like image 333
Giovane Avatar asked Sep 30 '13 11:09

Giovane


2 Answers

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.

like image 97
Pieter Avatar answered Sep 19 '22 15:09

Pieter


You can use the overloaded EntityManager#createNativeQuery(sql,resultClass) method for this.

like image 39
Rahul Avatar answered Sep 20 '22 15:09

Rahul