此前我們已經介紹了HibernateTemplate的使用配置方法,但是對其使用沒有仔細說明。因為最近比較忙,我先不去介紹,而是重點說明一下容易引起問題的findByExample方法。
我嘗試反編譯HibernateTemplate去直接找到findByExample()方法的實現,但是發現其基於多個其他API,最主要是Hibernate提供的Criteria類,因此我只打算簡單說明一下findByExample這個方法的適用范圍。
- findByExample()會忽略所有值為null的參數,但如果參數包含8種基礎類型,它們的默認空值不是null,這樣就會導致錯誤。所以,請不要將帶有基礎類型變量的bean用於findByExample。
- findByExample()不支持主鍵。
當我們想要通過主鍵查詢一個值時,應當適用HibernateTemplate提供的Object get(String entityClassName, Serializable id)方法,前者是所查的表的實例的類名(注意不是真實的表名),后者為主鍵。
如果我們一定要在findByExample()方法中結合主鍵的查詢(就是對已經寫好的出了問題的代碼背鍋......)可以這樣:
public List findByExample(UserEntity userEntity) {
if (userEntity.getAccountNumber() != null)
return hibernateTemplate.find("from UserEntity userEntity where userEntity.accountNumber=" + userEntity.getAccountNumber());
return hibernateTemplate.findByExample(userEntity);
}
在用example查詢前手動執行一次主鍵查詢。