2012-06-25 18 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设计和单元测试来确保始终设置一个值,例如,将此值作为构造函数的参数。根据你的推理,如果你忘记了非空约束,你也会得到不好的数据(和坏对象设计)。忘记事情会发生,并导致错误。纠正错误,但不要妥协好的面向对象设计,希望这会导致更少的错误。 –

相关问题