Hibernate可以将Null字符串默认为空字符串

时间:2010-04-14 15:09:30

标签: java hibernate orm db2 castor

在我们的应用程序中,我们从DB2大型机数据库中提取数据。如果数据库在字段中具有“低值”,则hibernate在对象中发送“null”值。即使将列定义为“非null”,也会发生这种情况。

由于我们正在对此进行XML解析,因此Castor遇到了麻烦。我想在Hibernate中解决这个问题。此外,所有hibernate hbm文件都是生成的,所以我们不能搞乱它们(它们会不时被重新生成。)

任何方法拦截所有字符串并用“”替换空值?

以下是我们提出的解决方案。实际上,这是一个大写的并且被截断(删除了许多抽象方法)。

 public class UpperCaseUserType implements org.hibernate.usertype.UserType{
    private static final int[] TYPES = {Types.VARCHAR};

    public Object nullSafeGet(ResultSet resultSet, String[] strings, Object object) throws HibernateException, SQLException {
        //This might be redundant to uppercase the getter...
        return StringUtils.upperCase((String) Hibernate.STRING.nullSafeGet(resultSet, strings[0]));
    }
    public void nullSafeSet(PreparedStatement preparedStatement, Object object, int i) throws HibernateException, SQLException {
        String string = StringUtils.upperCase((String) object);
        Hibernate.STRING.nullSafeSet(preparedStatement, string, i);
    }
}

然后你用这种方式把它连接起来:

 <property name="partNumber" type="cat.dds.fpsdma.model.UpperCaseUserType">
        <column name="PART_NUMBER" length="20" not-null="true" />
 </property>

4 个答案:

答案 0 :(得分:2)

  • 创建自定义用户类型,将null替换为""
  • 将用户类型名称放在通常在reveng.xml中添加休眠类型名称的位置。

答案 1 :(得分:1)

这是我们(向@Betlista@markthegrea致谢)提出的解决方案。实际上,这是一种大写形式,并且会被截断(删除了许多抽象方法)。

 public class UpperCaseUserType implements org.hibernate.usertype.UserType{
    private static final int[] TYPES = {Types.VARCHAR};

    public Object nullSafeGet(ResultSet resultSet, String[] strings, Object object) throws HibernateException, SQLException {
        //This might be redundant to uppercase the getter...
        return StringUtils.upperCase((String) Hibernate.STRING.nullSafeGet(resultSet, strings[0]));
    }
    public void nullSafeSet(PreparedStatement preparedStatement, Object object, int i) throws HibernateException, SQLException {
        String string = StringUtils.upperCase((String) object);
        Hibernate.STRING.nullSafeSet(preparedStatement, string, i);
    }
}

然后您以这种方式进行连接:

 <property name="partNumber" type="cat.dds.fpsdma.model.UpperCaseUserType">
        <column name="PART_NUMBER" length="20" not-null="true" />
 </property>

答案 2 :(得分:0)

您可以使用扩展EmptyInterceptor的hibernate拦截器在实际触发该查询之前执行您想要的操作。

这里给出的例子可以帮助你

http://www.mkyong.com/hibernate/hibernate-interceptor-example-audit-log/

答案 3 :(得分:0)

我可以通过简单地处理连接器设置程序中的数据库NULL值来解决同一方面的问题,如建议的here

/**
 * Set the value related to the column: NOM
 * @param nom the NOM value
 */
public void setNom (String nom) {
    this.nom = (nom!= null) ? nom : "" ;
}
相关问题