Using dynamic instantiation In Hibernate

2008-02-23 09:13:23来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

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.

上一篇: 多线程编程的设计模式 临界区模式(一)
下一篇: javascript实现划词标记 划词搜索功能

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:SpringSide 2.0 RoadMap

下一篇:多线程编程的设计模式 临界区模式(一)