0

How to add regexp in MySQL for a select query in hibernate. I am using ajax data table. my project is in spring 4 MVC and Hibernate with MySQL. I already create this in hibernate with MongoDB but I don't know how to use in MySQL.

hibernate with mongodb code:

Query query = new Query();
query.addCriteria(Criteria.where("isDeleted").is(IsDeletedEnum.NOTDELETED));
String search = (String) rowStartIdxAndCount[4];
if (StringUtils.isNotBlank(search)) {
    String searchExp = ".*" + search + ".*";
    Criteria searchCriteria = new Criteria();
    searchCriteria.orOperator(Criteria.where("name").regex(searchExp, "i"),
        Criteria.where("mobileno").regex(searchExp, "i"),
        Criteria.where("email").regex(searchExp, "i"),
        Criteria.where("role").regex(searchExp, "i"));
    query.addCriteria(searchCriteria);
}

and I am trying in Hibernate with MySQL. but no idea what's next that I have to write? I have to add regex in name, mobileno, email and role field which is used with or operator.

    Session session = getSessionFactory().openSession();
    session.beginTransaction();
    String search = (String) rowStartIdxAndCount[4];
    String searchExp = ".*" + search + ".*";
    String hql ="SELECT * FROM UserBean WHERE isDeleted=isDeleted OR name REGEXP 'searchExp''i'";
    Query query = session.createQuery(hql);
    query.setParameter("isDeleted", IsDeletedEnum.NOTDELETED);

so how to do that? please help me.

3
  • do you mean how to search operation on multiple column ? @Harsh in hibernate Commented Aug 30, 2017 at 6:23
  • yes, but with or operation and regular expression.you can see MongoDB code.that was criteria based query and I have to create hql based query. Commented Aug 30, 2017 at 6:25
  • give me SQL I convert it to HQL. I am not much familiar with NoSQL Commented Aug 31, 2017 at 6:56

1 Answer 1

3

Make criteria one by one:

criteria1
.setProjection(Projections.property("name"))
.add(Restrictions.sqlRestriction("REGEXP pattern")

criteria2
.setProjection(Projections.property("mobileno"))
.add(Restrictions.sqlRestriction("REGEXP pattern")

criteria3
.setProjection(Projections.property("email"))
.add(Restrictions.sqlRestriction("REGEXP pattern")

criteria4
.setProjection(Projections.property("role"))
.add(Restrictions.sqlRestriction("REGEXP pattern")

After that add those criteria to hibernate query:

query.addCriteria(criteria1);
query.addCriteria(criteria2);
query.addCriteria(criteria3);
query.addCriteria(criteria4);
Sign up to request clarification or add additional context in comments.

1 Comment

how to add (searchExp, "i") in a regular expression? I have to add both in that.and is there any other way for creating it in HQL query based?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.