Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlResultSetMapping columns as and entities

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.

like image 593
SoftwareSavant Avatar asked Jul 12 '12 13:07

SoftwareSavant


1 Answers

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];
}
like image 185
gamliela Avatar answered Sep 23 '22 16:09

gamliela