int類型屬性判空


在用Hibernate開發查詢時遇到的問題,方法的輸入參數為一個User對象,其中status和permission屬性為int型,

在進行junit單元測試時,只設置email一個參數,測試程序報錯,debug進去看后發現new的對象的int類型的屬性都是0,java把int類型的屬性都初始化為0了.

因為在頁面上也有status和permission屬性的查詢條件輸入,這時就有一個問題,當頁面不輸入status和permission兩個查詢條件時,后台service無法判斷是否為空,,因為都是0

 1 String sql = "select U from User U where 1 = 1 ";
 2         if(u.getEmail() != null && !u.getEmail().equals("")) {
 3             sql += " and U.email = '" + u.getEmail() + "'";
 4         } 
 5         if(u.getName() != null && !u.getName().equals("")) {
 6             sql += " and U.name = '" + u.getName() + "'";
 7         }
 8         if(u.getGender() != null) {
 9             sql += " and U.gender = '" +u.getGender()+ "'";
10         }
11         if(u.getStartBirthdate() != null) {
12             sql += " and U.birthdate >= " + u.getStartBirthdate() + "'";
13         }
14         if(u.getEndBirthdate() != null) {
15             sql += " and U.birthdate <= " + u.getEndBirthdate() + "'";
16         }
17         if(u.getStatus() != null) {
18             sql += " and U.status = " + u.getStatus() + "'";
19         }
20         if(u.getPermission() != null) {
21             sql += " and U.permission = '" + u.getPermission() + "'";
22         }
23         Query query = session.createQuery(sql);
24         
25         if(u.getStart() == null) {
26             u.setStart(0);
27         }
28         if(u.getLimit() == null) {
29             u.setLimit(10);
30         }

因為int類型的屬性會在new對象時自動初始化為0,無法判空

我的解決辦法是在實體類中把int類型改為Integer類型,Integer是java類,在初始化時被初始為null,這樣就解決了查詢條件永遠為0的問題.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM