【问题标题】:Lowercase annotation in HibernateHibernate 中的小写注释
【发布时间】:2012-10-28 11:50:16
【问题描述】:

在休眠中有什么方法可以将实体的列注释为字符串小写?我的意思是例如

@Entity  
public class User {  
    @Column  
    private String username;  
}

我希望 hibernate 在所有未绑定到特定数据库的查询中将用户名转换为小写。

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    例如,您可以在 setter 中制作:

    public void setUsername(String username) {
        this.username = username.toLowerCase();
    }
    

    或者使用interseptor:

        public boolean onSave(Object entity,Serializable id, Object[] state,String[] propertyNames,Type[] types) throws CallbackException {
        if (entity instanceof User ){
            entity.username = usename.toLowerCase();
        }
        return false;
    }
    

    您可以在此处阅读有关拦截器的更多信息: http://www.mkyong.com/hibernate/hibernate-interceptor-example-audit-log/

    【讨论】:

      【解决方案2】:

      你可以为这个字符串写自己的UserType

      public class LowerCaseString implements UserType
       {  
           //....  
              public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index)
                  throws HibernateException, SQLException {
              Hibernate.STRING.nullSafeSet(preparedStatement, 
                      (value != null) ? ((String)value).toLowerCase() : null, index);
               }  
          ///....  
      }  
      

      你的实体

      @Entity  
      public class User {  
          @Column  
          @Type(type="com.youcompany.LowerCaseString")
          private String username;  
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-25
        • 2011-12-07
        • 2011-06-03
        • 2011-10-04
        • 1970-01-01
        • 2011-02-26
        • 2017-05-22
        • 1970-01-01
        • 2015-02-03
        相关资源
        最近更新 更多