ssh项目中,我们在前台页面展示数据的时候,经常会用到VO类.也就是把要展示 的数据封装成为VO对象.这样我们在前台页面从VO对象中取数据.我们通过hql查询.往往不会需要查询出实体的全部属性.那么我们如果查询出部分属 性.hibernate会自动帮你封装成为object对象[].可是,我们想直接用对象怎么办?难道还要一个一个的setter循环赋值给VO吗.不用 了.下面我们看看怎么在查询结果中显示列名.怎么将查询的结果直接封装成VO
先看我的VO类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
class
SureOrder {
private
Integer prodid;
//商品id
private
String name;
//商品名
private
String imgurl;
//图片
private
double
cuxiaoPrice;
//赠送积分
private
double
price;
//市场价
private
double
newprice;
//会员价
private
String guiGe;
//规格
private
double
orderPirce;
//下单费 扣除会员
private
double
believeMoney;
//爽约金
private
Date believerTime;
//爽约时间
private
double
puish;
//违约金=此值+爽约金
private
Integer nums;
//购买数量
private
Integer typeid;
//1:现场结算/2:储值结算
private
String note;
//备注
private
String pinPai;
//品牌
private
Integer types;
//类型 1=会员非标产品 3=标准产品 2=工商非标产品(默认:3)
private
Integer nodeId;
//小区邻郎ID
private
Integer qianyueId;
//签约店id
private
Integer proId;
//商品id
private
Integer factId;
//生产企业id
private
double
subtotal;
//小计
|
上面是所有的VO属性.在下面的hql语句中.as列的别名一定要用和VO类里面的列名一样.可以不返回.但是你如果返回就必须一样.因为你想用hibernate自动帮你封装成VO实体.hibernate底层也是通过setter方法自动帮你赋值的.
再看DAO:
1
2
3
4
5
6
7
|
public
Query getProductDetail(Integer productId,String hql) {
logger.debug(
"********************getProductDetail方法begin****************************"
);
Query query = getSession().createQuery(hql);
query.setInteger(
0
, productId);
logger.debug(
"********************getProductDetail方法end****************************"
);
return
query;
}
|
dao层,我返回了一个query对象.我这样做是为了将所有的数据封装都放在了service.
接着看service:
1
2
3
4
5
6
7
8
9
10
|
public
SureOrder getSureOrderVO(Integer productId) {
String hql =
"select pd.id as prodid,pd.cuxiaoPrice as cuxiaoPrice,pd.types as types,pd.price as price,pd.newprice as newprice,p.nodeId,p.imgurl as imgurl,p.types as types,p.factId as factId,p.qianYueId as qianyueId,p.guiGe as guiGe,p.name as name,p.pinPai as pinPai from Product pd,Prod p where p.id=pd.prodId and pd.id =?"
;
Query query = productDao.getProductDetail(productId,hql);
//主要起作用的就是下面的这个方法:SureOrder是我要封装的VO类.这样hibernate在执行hql查询的时候,会直接将结果封装为SureOrder对象.
List list = query.setResultTransformer(Transformers.aliasToBean(SureOrder.
class
)).list();
if
(!list.isEmpty()){
return
(SureOrder) list.get(
0
);
}
return
null
;
}
|
看一下打印输出的语句:
1
|
订单信息:{
"believeMoney"
:
0
,
"cuxiaoPrice"
:
10
,
"factId"
:
411
,
"guiGe"
:
"40*20*12"
,
"imgurl"
:
"prodpric/logo.png"
,
"name"
:
"电池"
,
"newprice"
:
800
,
"nums"
:
1
,
"orderPirce"
:
0
,
"pinPai"
:
"万里"
,
"price"
:
1000
,
"prodid"
:
104
,
"puish"
:
0
,
"qianyueId"
:
439
,
"subtotal"
:
800
,
"types"
:
3
}
|
看到了吗.列名出来了.并且都是键值对的方式.很方便我们用.不管你是用json序列化还是转换为VO类.很方便.不用去一个一个循环.并且对号setter了.