Search code examples
hibernatehibernate-searchadvanced-search

Advanced Search Using Hibernate Search


In one of my applications, I am to execute a search on multiple fields/columns. Its an Advanced Search and there are over 20 fields using which a user can search for results. For example, a user can search for bookings based on

  1. Booking Id
  2. Passenger Name
  3. Passenger Age
  4. From Location
  5. To Location
  6. Booking Status
  7. Name of the Airline

and 13 such fields.

I am trying to figure out if

  1. Hibernate Search can and should be used here? If so, how? I was unable to find an example for such a complex search using Hibernate Search.

  2. Instead of Hibernate search, I can simply use Hibernate and maybe design a multi-threaded search depending in the number of parameters. Would that be a good idea?

  3. Is it possible to use Hibernate Filters here?

Can someone please provide inputs or reference links?


Solution

  • For these kinds of queries, I generally use a Criteria query with a form object. I then check for null in each passed form field, and if not null, then add another Restriction into the query, using that field. Using a Criteria query keeps the Java code very clean and eliminates messy string concatenation. An example for your case:

    // Form object
    public class bookingSearchForm {
        private String bookingId;
        public getBookingId()...
        public setBookingId()...
    }
    
    // Hibernate
    Criteria criteria = getSession().createCriteria(Booking.class);
    if(form.getBookingId() != null) {
        criteria.add(Restrictions.eq("bookingId", form.getBookingId()));
    }
    criteria.list();