Question

I have an Entity called User:

public class User {
    private String title;
}

I provide a text field to my clients. when they type in a phrase I would like to find all User entities whose names include the given phrase.

For example consider having list of entries in database with following titles:

[ Alan Smith, John Cane, Juno Taylor, Tom Caner Junior ]


jun should return Juno Taylor, and Tom Caner Junior

an should return Alan Smith, John Cane, and Tom Caner Junior

It is possible to do this by loading all user entries from database and then check if the title contains the given phrase, but I may have numerous users on the system and loading all of them seems not to be a good choice.

Hence I want to handle this in database layer and preferably with Hibernate Criteria of some sort. Please let me know if this makes any scene and is there a cost effective way to achieve this.

Was it helpful?

Solution

You want to use an ilike restriction.

Something along the lines of

String value = "jun";
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.ilike("title", value, MatchMode.ANYWHERE);

should do the trick.

I don't know how efficient it is, and it may well vary depending on your DB (esp as it mimicks something actually available in Postgres, and may use that operator in the postgres dialect). It's probably better than getting everything and filtering in Java though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top