[解決方法]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