Question

I want to search the contents in a forum especially forum questions

for example:

searchString = "Hibernate Session Configuration"; 

will give corresponding details in the Forum Questions

but all the words need not to be consecutive in the forum content and so i am storing the searching string in a java.util.Set containing each word

String[] searchArray= searchString.toLowerCase().split(" ");
Set<String> searchSet = new HashSet<String>();

// searchSet contains words of searchString
for(String string : searchArray){
searchSet.add(string);
}

I written hibernate query as,

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ForumQuestion.class);

for(String searchUnitString : searchSet)
{
detachedCriteria= detachedCriteria.add(Restrictions.disjunction().add(Restrictions.ilike("forumQuestion", "%"+searchUnitString+"%")));
}
return template.findByCriteria(detachedCriteria);

But this query is not working properly.. it just take the last Restrictions ignoring the previous Restrictions!

In this example, it will consider only for '%Configuration%' but my need is '%Hibernate%' or '%Session%' or '%Configuratoin%' together

Note: if I query for each word, then database hit will be high

Was it helpful?

Solution

You're not adding a disjunction. You're adding N disjunctions containing only one restriction each. The code should be:

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ForumQuestion.class);
Disjunction disjunction = Restrictions.disjunction();
for (String searchUnitString : searchSet) {
     disjunction.add(Restrictions.ilike("forumQuestion", "%"+searchUnitString+"%"));
}
detachedCriteria.add(disjunction);
return template.findByCriteria(detachedCriteria);

Note that unless you have few questions in your forum, these searches will be slow. SQL queries are not the best way to handle full text search. I would look at Lucene (that Hibernate Search uses, BTW) for such a task.

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