hibernate實體類屬性應該使用int還是Integer
阿新 • • 發佈:2019-02-19
我們知道,hibernate並沒有強制要求pojo(實體類 )屬性必須是基本資料型別或者是包裝類,但是我們把屬性宣告為基本資料型別( primitive types directly)或者包裝類 ( wrapping classes for primitives)對我們程式碼的編寫有著深遠的影響。
下面引用自hibernate官方文件
Cat has a property called id. This property maps to the primary key column(s) of a database table. The property might have been called anything, and its type might have been any primitive type, any primitive "wrapper" type, java.lang.String or java.util.Date.
...
We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type.
可以看出,hibernate是建議開發者使用包裝類的。
a),如果你的資料庫欄位是允許為空的,使用包裝類。如果不允許為空,使用包裝的時候,如果你往資料庫插入null值,此時就會丟擲異常。然後你就可以對異常進行捕獲並處理。
b),使用基本資料型別的時候,如果欄位是NULL,那麼JDBC會返回0,但是這裡會有一個問題。有可能0在你的業務邏輯代表著特定含義,這時候就可能出現一些意想不到的後果。
總結:在專案中去使用包裝型別而不是基本資料型別,這樣可以使你編寫程式碼更簡單,除非有人給你一個更好的理由去使用基本資料型別或者你的上頭要求一定要使用基本資料型別。
轉載地址:http://www.cnblogs.com/chenxie/archive/2016/04/28/5444336.html