Alo*_*ali 3 java null netbeans hibernate
我试图将数据库中的字段更新为null为整数字段.我试图用hibernate做到这一点.我可以将像String这样的对象字段和任何其他对象设置为null但不是整数.
<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
在上面的hibernate映射代码中,我想将MasterOrg字段设置为null.
最好使用原始类型的对象包装器,即Integer for int,Double for double,... etc,因为原始类型不允许null的可能性,这在数据库设计中总是可行的.
即使在数据库中声明的值不为null,Object类仍然有用.以下面的场景为例.
@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
Run Code Online (Sandbox Code Playgroud)
}
假设您编写以下代码
ExampleEntity t = new ExampleEntity();
entityManager.persist(t);
Run Code Online (Sandbox Code Playgroud)
在此示例中,t.someProperty的值为0,因为这是int的默认值,因此entityManager.persist可以工作,但可能0不是该列的有效值.如果您对该列有数据库约束,那么您将收到错误,否则您在数据库中有错误的数据.
如果someProperty是使用Integer的包装类型声明的,并且开发人员忘记设置somePorpety值,那么您将获得一个非null异常.
总是使用包装器的第二个原因是作为开发人员的简单性我想要跨实体的一致结构,因为代码被更频繁地读取,因此通常使用实体上的包装器类型来编写,这使得可以预测5年后维护代码的某些人.
| 归档时间: |
|
| 查看次数: |
8419 次 |
| 最近记录: |