2012-06-25 19 views
3

我正在嘗試將數據庫中的字段更新爲空字段。我正在嘗試使用hibernate來做到這一點。我可以設置對象字段像String和任何其他對象爲null,但沒有整數。如何使用hibernate在整數字段的數據庫中設置空值?

<?xml version="1.0" encoding="UTF-8"?> 

<class name="App_Users" table="app_users" schema="bidtool"> 

    <id name="userId" type="int" column="user_id">   
     <generator class="assigned"/> 
    </id> 

    <property name="username" type="string"> 
     <column name="username" length="20" not-null="true" /> 
    </property> 
    <property name="password" type="string"> 
     <column name="password" length="20" not-null="true" /> 
    </property> 
    <property name="firstname" type="string"> 
     <column name="firstname" length="20" /> 
    </property> 
    <property name="lastname" type="string"> 
     <column name="lastname" length="20" /> 
    </property> 
    <property name="userType" type="int"> 
     <column name="user_type" /> 
    </property> 

    <many-to-one class="MasterOrg" fetch="select" name="masterOrg"> 
     <column name="master_org_id" /> 
    </many-to-one> 

    <many-to-one class="CarrierScac" fetch="select" name="carrierScac"> 
     <column name="scac" /> 
    </many-to-one> 


    <one-to-one class="AppUserDetails" fetch="select" name="details" constrained="true"/> 

    <set name="profiles" inverse="true"> 
     <key> 
      <column name="user_id" /> 
     </key> 
     <one-to-many class="Profiles" /> 
    </set> 

    <set name="boilerPlates" inverse="true"> 
     <key> 
      <column name="user_id" /> 
     </key> 
     <one-to-many class="BoilerPlate" /> 
    </set> 


    <set name="rates" inverse="true" > 
     <key> 
      <column name="user_id" /> 
     </key> 
     <one-to-many class="BidToolRates" /> 
    </set> 


</class>  


在上述休眠映射代碼,我想設置MasterOrg字段爲空。

+0

您的數據庫模式是否允許'master_org_id'列的NULL值?也許它被定義爲使用默認值。只要你引用'App_User.masterOrg = null',它應該只是工作 – Brad

+0

@JoeriHendrickx我試着用空值插入空值到數據庫中。數據庫中的字段的類型爲基本int。我需要在int類型的字段中插入null。 –

+0

@Brad是的,我的數據庫模式允許master_org_id列的空值。我認爲這個問題正在被創建,因爲master_org_id的類型是int。它適用於String和其他對象類型 –

回答

5

對於原始類型最好使用對象包裝器,即Integer for int,Double for double,...等,因爲基元類型不允許在數據庫設計中始終可能存在null的可能性。

即使數據庫中的值聲明爲非空,對象類型仍然有用。以下面的情況爲例。

@Entity 
public class ExampleEntity { 
    @Column(name="some_column") // assume this column is defined not null in the database 
    private int someProperty; 

    getttes settters other fields go here 

}

假設你寫下面的代碼

ExampleEntity t = new ExampleEntity(); 
entityManager.persist(t); 

在這個例子中t.someProperty具有0值,因爲這是一個int的默認值,因此entityManager.persist作品但也許0不是該列的有效值。如果你對該列有數據庫限制,那麼你會得到一個錯誤,否則你有數據庫中的錯誤數據。

如果someProperty聲明爲Integer的包裝類型,並且開發人員忘記設置somePorpety值,那麼您將得到一個非null異常。

總是使用包裝的第二個原因是開發人員希望簡單,因爲我希望跨實體採用一致的結構,因爲代碼被更頻繁地讀取,使用實體上的包裝類型進行普遍編寫使得某些人可以預測維護代碼5年現在起。

+0

最好對可空列使用對象包裝器,對不可空對象列使用基本類型。爲什麼我會強制我的實體的所有用戶處理可能的空值,如果該值不能爲空? –

+0

@JB看到我更新的答案。 – ams

+2

我完全不同意。例如,如果0不是可接受的默認值,那麼使用適當的OO設計和單元測試來確保始終設置一個值,例如,將此值作爲構造函數的參數。根據你的推理,如果你忘記了非空約束,你也會得到不好的數據(和壞對象設計)。忘記事情會發生,並導致錯誤。糾正錯誤,但不要妥協好的面向對象設計,希望這會導致更少的錯誤。 –

相關問題