扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:每天都是起点 来源:CSDN 2008年3月17日
关键字: instantiation dynamic java
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.
婵″倹鐏夐幃銊╂姜鐢瓕鎻╅崚鍥╂畱閹厖绨$憴顤廡妫板棗鐓欓張鈧弬棰侀獓閸濅椒绗岄幎鈧張顖欎繆閹垽绱濋柇锝勭疄鐠併垽妲勯懛鎶姐€婄純鎴炲Η閺堫垶鍋栨禒璺虹殺閺勵垱鍋嶉惃鍕付娴f娊鈧柨绶炴稊瀣╃閵嗭拷
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者