配置最后的形式:
@SqlResultSetMapping
(
name = "ItemResults",
entities = {
@EntityResult(
entityClass = Item.class, //就是当前这个类的名字
fields = {
@FieldResult(name = "id", column = "id"),
@FieldResult(name = "itemId", column = "item_id"),
}
)
},
columns = {
@ColumnResult(name = "item_id")
}
)
@Entity
@Table(name="item_permission")
public class Item implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
@Column(name="item_id")
private Integer itemId;
public Item(){}
}
查询
public ItemDAO{
ItemPermissionDAO dao = new ItemPermissionDAO();
Query query = dao.getEntityManager().createNativeQuery(
"select * from item_permission", "ItemResults");
@SuppressWarnings("unchecked")
List<Object[]> items = query.getResultList();
for (Object[] item : items) {
System.out.println(item[1]);
}
}
它返回的格式是Object[]的数组形式
{ [, ] ,[, ] }
而且需要注意的是:
@EntityResult(
entityClass = Item.class, //就是当前这个类的名字
fields = {
@FieldResult(name = "id", column = "id"),
@FieldResult(name = "itemId", column = "item_id"),
}
)
其中注解FieldResult的配置必须是整个entity的所有属性的配置。在当前中属性有两个一个是id,另一个是itemId。所以FieldResult有两个。如果不写全的话,就会异常抛出。