I am trying to do the following query using Hibernate Criteria
SELECT * FROM EUser
WHERE
userName LIKE '%mat%' OR
firstName LIKE '%mat%' OR
lastName LIKE '%mat%' OR
middleName LIKE '%mat%' AND
enable = 'ACTIVE';
Now I can Use query like following (//found by googling)
Criteria criteria = session.createCriteria(EUser.class);
Criterion roll = Restrictions.eq("rollNo", 2);
Criterion name = Restrictions.eq("name", "John");
LogicalExpression expression = Restrictions.or(roll, name);
criteria.add(expression);
List list = criteria.list();
Criteria criteria = session.createCriteria(EUser.class);
Criterion roll = Restrictions.eq("rollNo", 1);
Criterion name = Restrictions.eq("name", "John");
LogicalExpression expression = Restrictions.and(roll, name);
criteria.add(expression);
List list = criteria.list();
But it seems too much coding for so little query
Is there any simpler code to achieve this??
This is your actual query, slightly more succint.
session.createCriteria(EUser.class)
.add(Restrictions.disjunction()
.add(Restrictions.like("userName", "mat%"))
.add(Restrictions.like("firstName", "mat%"))
.add(Restrictions.like("lastName", "mat%"))
.add(Restrictions.like("middleName", "mat%")))
.add(Restrictions.eq("enable ", "active"))
.list();
Rather wordy, but does keep your code nice an oop and easy to do dynamic and generic queries.
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<EUser> criteriaQuery = criteriaBuilder.createQuery(EUser.class);
Root<EUser> root = getRoot(criteriaQuery);
Path<String> userName = root.get("userName");
Path<String> firstName = root.get("firstName");
Path<String> lastName = root.get("lastName");
Path<String> middleName = root.get("middleName");
Path<String> enable = root.get("enable");
Predicate userNamePredicate = criteriaBuilder.like(userName, "%mat%");
Predicate firstNamePredicate = criteriaBuilder.like(firstName, "%mat%");
Predicate lastNamePredicate = criteriaBuilder.like(lastName, "%mat%");
Predicate middleNamePredicate = criteriaBuilder.like(middleName, "%mat%");
Predicate enablePredicate = criteriaBuilder.equal(enable, "ACTIVE");
Predicate middleNameAndEnablePredicate = criteriaBuilder.and(middleNamePredicate, enablePredicate);
Predicate predicate = criteriaBuilder.or(userNamePredicate, firstNamePredicate, lastNamePredicate, middleNameAndEnablePredicate);
criteriaQuery
.select(root)
.where(predicate);
List<EUser> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With