【问题标题】:Hibernate Criteria for different field value length不同字段值长度的休眠条件
【发布时间】: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 个字符。
  • 代码是一个简单的字符串“字符串代码;” . “长度”只是为了可视化我想要归档的内容

标签: java hibernate criteria


【解决方案1】:

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

并在条件中使用 codeLength。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2011-06-17
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    相关资源
    最近更新 更多