Search code examples
javahibernatecriteria

Hibernate Criteria for different field value length


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

Solution

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

    and use the codeLength in the criteria.