[解决方法]Hibernate查询部分字段(含外键)出错,报空指针异常


假设当前表结构如下:

  food表字段有foodid,name,外键businessid,外键type

  business表字段有,name,外键type

  type表字段有id,name,foodid

 

Hibernate生成的对应POJO分别是Food,Business,Type

 

需要查询food表部分字段,如name和外键businessid

  则可在Food类中添加只有相应成员变量的构造方法,Food(String name,Business business)

使用hql语句 

select new Food(name,business) from Food where foodid=1

 

 

以上可以顺利查询,但是如果调换name和顺序

使用Food(Business business,String name)

hql语句 

select new Food(business, name) from Food where foodid=1

就会报空指针异常

 

这其实是因为外键的关联表Business中也含有叫name的字段,所以会发生错误,此时只要给查询表使用别名就可以解决了.

正确的语句:

select new Food(f.business, f.name) from Food f where foodid=1

 

同理,如果也查询外键type, 那么:

错误的语句:

select new Food(name,business,type) from Food where foodid=1

 

正确的语句:

select new Food(f.name,f.business,f.type) from Food f where f.foodid=1

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM