不同字段值长度的 Hibernate 标准

Hibernate Criteria for different field value length

我有一个实体,它有一个大小为 10 的(字符串)字段

@Column(length = 10)
String code;

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

final List<String> codesLong= new ArrayList<String>();
final List<String> codesShort= new ArrayList<String>();
...
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<String> codesLong= new ArrayList<String>();
final List<String> codesShort= new ArrayList<String>();
...
criteria.add(Restrictions.or(
Restrictions.and(Restrictions.in("code", codesShort),
Restrictions.eq("codelength", 5)),
Restrictions.and(Restrictions.in("code", codesLong),
Restrictions.eq("codelength", 10)))
);

可以引入一个人工的Entity字段codeLength并使用@Formula注解(例子here

并在条件中使用 codeLength。