Gopi Krishna Seeram
Gopi Krishna Seeram

Reputation: 131

How to perform search operation on two fields with same keyword in hql?

I am not getting the record if any one of the field in data base is null whether the company name or location. Here keyword is what I am entering from the form.

This is my query:

Query qry=session.createQuery("select distinct company_name from Company_Info where company_name like '%"+keyword+"%' or  locations.city like '%"+keyword+"%'");

Does anybody know how to make this work?

Upvotes: 0

Views: 190

Answers (2)

Gopi Krishna Seeram
Gopi Krishna Seeram

Reputation: 131

I achieved by using apache lucene search it's worked for me:

FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer(Company_Info.class).startAndWait();

QueryBuilder qb = fullTextSession.getSearchFactory()
    .buildQueryBuilder().forEntity(Company.class).get();
org.apache.lucene.search.Query query = qb.keyword()
        .onFields("company_name","locations.city")
        .matching(keyword)
    .createQuery();

org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, Company_Info.class);

List<Company_Info> result = hibQuery.list();

Upvotes: 1

Dark Knight
Dark Knight

Reputation: 8357

Since you have to use is null in the HQL, (if there are parameters with null potential.) Use this:

String keywordTerm = keyword==null ? "is null" : "= :keyword";

Query qry=session.createQuery("select distinct company_name from Company_Info where company_name like '%"+keyword+"%' or  locations.city like '%"+keyword+"%'");

if(keyword!=null){
    qry.setParameter("keyword", keyword, Hibernate.STRING)
}

Upvotes: 1

Related Questions