在Hibernate映射中:如何设置默认值?

时间:2014-04-08 11:00:52

标签: java hibernate hibernate-mapping

  

在我的项目中,我想设置三列的默认值,我在x.hbm.xml文件中使用此代码:

<property name="occupation" type="string">
        <column name="occupation" length="20" not-null="false" default="Not Provided" />
    </property><property name="address" type="string">
        <column name="address" length="150" not-null="false" default="Not Provided"  />
    </property><property name="contact" type="string">
        <column name="contact" length="15" not-null="false" default="Not Provided" />
    </property>
  

当用户没有提供所有三个值时,只有第一个(占用)被设置为默认值而其他不是..或者更多然后没有提供一个字段然后只有一个列获得默认值而不是..

3 个答案:

答案 0 :(得分:1)

我使用注释尝试了它。

@Column(name = "colName", insertable=false, updatable = false, nullable = false, 
        columnDefinition = "varchar(255) default '14-APR-1981'") 

或者您可以使用@PrePersist注释

@PrePersist
public void prePersist() {
if(myProperty == null) //We set default value in case if the value is not set yet.
    myProperty = "Default value";
}

答案 1 :(得分:0)

这不是设置您提出的默认值,但如果一个或多个字段为空,则设置一个字段为“未提供”字符串。是吗?

最简单的理解方法是修改构造函数和setter,以便手动过滤它,如下所示:

public class YourTable {
  private String occupation;
  private String address;
  private String contact;

  public YourTable (){
    checkNull();
  }

  //your geter setter here, and each setter must call checkNull() method after setting it's value

  private void checkNull(){
    if(occupation==null){
      occupation="Not Provided";
      return;
    }
    if(address==null){
      address="Not Provided";
      return;
    }
    if(contact==null){
      contact="Not Provided";
      return;
    }
  }
}

答案 2 :(得分:0)

在servlet内部,我添加了此代码以检查用户是否未提供任何值,然后将其设置为“未提供”,然后插入值。

            if (occupation.equals("")) {
                occupation = "Not Provided";
            }
            if (address.equals("")) {
                address = "Not Provided";
            }
            if (contact.equals("")) {
                contact = "Not Provided";
            }