Suppose I have a simple table named "Book" with a column named "Title" VARCHAR(500).
[Books]
------------------------------------------------
|id | title |
------------------------------------------------
| 1 | "Gone with the Wind" |
| 2 | "The Stand" |
| 3 | "Standing at the edge" |
| 4 | "Standing at the edge of my sanity" |
------------------------------------------------|
So a search might be "standing edge" and should return books 3 and 4, or it could be "the" and return 1,2,3,4 or it could be "standing at the edge" and return 3 and 4.
I'm implementing a search page against this column where a user can enter multiple search terms.
I need to create a query against the book's title that returns all books with all given words in the title. The wrinkle is that there may be a variable number of search terms.
I'm new to Hibernate, and I can't come up with a more elegant solution than the following:
Code:
int numTerms = tmpListTerms.size();
String tmpSearchBy = "title";
switch(numTerms)
{
case 1: crit.add(Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(0), MatchMode.ANYWHERE)); break;
case 2: crit.add(Restrictions.or(Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(0), MatchMode.ANYWHERE),
Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(1), MatchMode.ANYWHERE))); break;
case 3: crit.add(Restrictions.or(
Restrictions.or(Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(0), MatchMode.ANYWHERE),
Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(1), MatchMode.ANYWHERE)),
Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(2), MatchMode.ANYWHERE))); break;
case 4: crit.add(Restrictions.or(
Restrictions.or(Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(0), MatchMode.ANYWHERE),
Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(1), MatchMode.ANYWHERE)),
Restrictions.like(tmpSearchBy, "" + tmpListTerms.get(2), MatchMode.ANYWHERE))); break;
case etc.... }
Specifically, I'm confused as to how to implement this logic that daisy chains "
Code:
Restriction.or()
" clauses for a variable number of search terms.
Is there a more elegant (and readable) solution?
I'm also confused about how to make the string comparison case insensitive.
Thanks for setting me straight,
-Tim
Hibernate version:
3.1