【发布时间】:2015-03-29 21:47:47
【问题描述】:
我有一个实体,它有一个大小为 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)))
);
但是...上面看起来不错,但显然行不通。我不知道如何处理这个问题。 如有任何提示,我将不胜感激。
谢谢
// 解决方案(感谢斯坦尼斯拉夫!) 实体:
@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)))
);
【问题讨论】:
-
code.length 指的是字符串或其他字符中的 no:of 个字符。
-
代码是一个简单的字符串“字符串代码;” . “长度”只是为了可视化我想要归档的内容