小编典典

不同字段值长度的休眠条件

hibernate

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

@Column(length = 10)
String code;

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

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)))
);

阅读 246

收藏
2020-06-20

共1个答案

小编典典

您可以引入人工的Entity字段codeLength并使用@Formula注释(此处为示例)

并在条件中使用codeLength。

2020-06-20