针对不同字段值长度的Hibernate Criteria

我有一个实体,其中(字符串)字段大小= 10

@Column(length = 10) String code; 

但是,字段的值长度可以是5或10.我想创建一个根据字段长度匹配该字段值的hibernate条件,如:

 final List codesLong= new ArrayList(); final List codesShort= new ArrayList(); ... criteria.add(Restrictions.or( Restrictions.and(Restrictions.in("code", codesShort), Restrictions.eq("code.length", 5)), Restrictions.and(Restrictions.in("code", codesLong), Restrictions.eq("code.length", 10))) ); 

但是……上面看起来不错,但显然不会起作用。 我不知道如何处理这个问题。 我会很感激任何提示。

谢谢

//解决方案(感谢Stanislav!)实体:

 @Column(length = 10) String code; @Formula(" length(code) ") int codelength; // create GETter method as well 

标准:

 final List codesLong= new ArrayList(); final List codesShort= new ArrayList(); ... criteria.add(Restrictions.or( Restrictions.and(Restrictions.in("code", codesShort), Restrictions.eq("codelength", 5)), Restrictions.and(Restrictions.in("code", codesLong), Restrictions.eq("codelength", 10))) ); 

您可以引入一个人工实体字段codeLength并使用@Formula注释( 此处示例)

并在条件中使用codeLength。