Using dynamic instantiation In Hibernate

hibernate中用select new 动态构造对象,如果select出的对象不是一个具体mapped对象,则hibernate返回一个

对象数组的list,要对每个数组元素cast,势必代码显得不够简捷和coarse-grained,下面的例子描述了如何实时构造java对象

Iterator i = session.createQuery(
"select item.id, item.description, bid.amount " +
"from Item item join item.bids bid " +
"where bid.amount > 100"
)
.list()
.iterator();
while ( i.hasNext() ) {
Object[] row = (Object[]) i.next();
Long id = (Long) row[0];
String description = (String) row[1];
BigDecimal amount = (BigDecimal) row[2];
// ... show values in a report screen
}

Since the previous example was verbose and not very object-oriented (working
with a tabular data representation in arrays), we can define a class to represent
each row of results and use the HQL select new construct:
select new ItemRow( item.id, item.description, bid.amount )
from Item item join item.bids bid
where bid.amount > 100
Assuming that the ItemRow class has an appropriate constructor (you have to write
that class), this query returns newly instantiated (transient) instances of ItemRow,
as you can see in the next example:
Iterator i = session.createQuery(
"select new ItemRow( item.id, item.description, bid.amount ) " +
"from Item item join item.bids bid " +
"where bid.amount > 100"
)
.list()
.iterator();
while ( i.hasNext() ) {
ItemRow row = (ItemRow) i.next();
// Do something
}
The custom ItemRow class doesn’t have to be a persistent class; it doesn’t have to be
mapped to the database or even be known to Hibernate. ItemRow is therefore only
a data-transfer class, useful in report generation.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值