Hibernate Criteria for different field value length

喜夏-厌秋 提交于 2019-12-06 08:05:14

问题


I've got an Entity which have a (string) field of size = 10

@Column(length = 10)
String code;

However, field's value length could be 5 or 10. I would like to create a hibernate criteria matching that field's value according to its length, like:

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

However... the above looks nice but, obviously, won't work. I do not know how to deal with that problem. I would be grateful for any hints.

thanks

// solution (thanks Stanislav!) Entity:

@Column(length = 10)
String code;

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

Criteria:

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

回答1:


You can introduce an artificial Entity field codeLength and use @Formula annotation (example here)

and use the codeLength in the criteria.



来源:https://stackoverflow.com/questions/28235541/hibernate-criteria-for-different-field-value-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!