SqlResultSetMapping columns as and entities
Asked Answered
D

1

8

I am really confused, how does column resultset mapping work? What am I mapping when I use columns instead of entities? Look at this 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")}
       )

I can understand what he is trying to do here, The Entity result will be the result set he wants, fields will try and map the fields to the aliased names, what the hell is column results doing? It doesn't look like it is mapping to anything.

Domesticity answered 12/7, 2012 at 13:11 Comment(0)
C
2

You map 4 fields from result set to 2 Java classes: first class is Order entity, and the second is (probably) String that shall contain "item_name" db field.

DB:                         Java
---                         ----
order_id              --->  \
order_quantity        --->  Order entity
order_item            --->  /
item_name             --->  String

In order to read the query results:

for (Object[] record : query.getResultList()) {
   Order order = (Order)record[0];
   String itemName = (String)record[1];
}
Clea answered 5/11, 2013 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.