其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
二:
/*
*对于getHibernateTemplate.find(hql)返回的list<SomeClass>
*如果hql中只select了SomeClass中的部分属性或者还包含其他表中的属性
*那返回的实际是一个新的类,这个类包含你所select的属性
*于是这个新类当然跟原本的SomeClass不相等
*此时如果把返回的list里的元素当做SomeClass来用的话
*会出现java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to SomeClass 错误
*/
实际上,作为面向对象工具,代码部分不必考虑实际表本身。这句话自己多实践几次就能真正体会出来。
/*
*正确用法
*/
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 错误
*/