ssh2项目中getHibernateTemplate().find常见错误小结

其hql与普通sql语句有不少差别。

实际上,作为面向对象工具,代码部分不必考虑实际表本身。这句话自己多实践几次就能真正体会出来。



一:

  
/*
 *正确用法
 */
String hql="select g.goodsid,g.goodsname from Goods g  where g.goodstype = ?";





/*
 *错误用法1
 */
String hql="select Goods.goodsid,Goods.goodsname  from Goods  where Goods.goodstype = ?";


//会出现Invalid path: 'null.goodsid'错误


/*
 *错误用法2
 *不能使用自定义的表格名而应使用bean名本身
 *否则会出现Login is not mapped错误
 */


/*
 *错误用法3
 *对于外键不能直接使用被关联类中的属性名或列名
 *应使用关联的类在原本类中的对象属性名本身
 *如Goods中有private Goodstype goodstype;
 *则此时应当用goodstype。
 */


//如有hbm
/*
<many-to-one name="goodstype" column="goodstypeid"
   class="Goodstype" not-null= "true"/>
*/
//则不应
String hql="select g.goodsid,g.goodsname  from Goods g where g.goodstypeid = ?
而应当用 g.goodstype = ?

//否则在这种many to one的情况下会出现could not resolve property



/*
 *另外,如果Goods与Goodstype已经进行了关联映射
 *那么选择Goods属性的同时还想选择Goodstype属性的时候不必增加from Goodstype
 *因为Goods类中的Goodstype属性会根据外键选择特定的Goodstype对应表中的行
 *此时从中获得相应属性即可
 */






二:
/*
 *对于getHibernateTemplate.find(hql)返回的list<SomeClass>
 *如果hql中只select了SomeClass中的部分属性或者还包含其他表中的属性
 *那返回的实际是一个新的类,这个类包含你所select的属性
 *于是这个新类当然跟原本的SomeClass不相等
 *此时如果把返回的list里的元素当做SomeClass来用的话
 *会出现java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to SomeClass 错误
 */


@Vincent____Tsang

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值