SqlResultSetMapping columns as and entities

陌路散爱 提交于 2019-11-30 04:24:57

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11452586/sqlresultsetmapping-columns-as-and-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!