SqlResultSetMapping columns as and entities

SoftwareSavant picture SoftwareSavant · Jul 12, 2012 · Viewed 9.1k times · Source

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.

Answer

gamliela picture gamliela · Nov 5, 2013

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];
}