Tags

, ,

Prerequisites to this blog post is to have a working knowledge of Hibernate‘s Session and Criteria.

QBE is very convenient for searches where the criterion is built from user input. It is best for advanced searches where multiple fields are at play.

For example, we have a Customer class as:

public class Customer
{
    private int    custId;
    private String firstName;
    private String lastName;
    private long   phone;
    private long   mobNo;

    public int getCustId()
    {
        return custId;
    }

    public void setCustId( int inCustId )
    {
        custId = inCustId;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName( String inFirstName )
    {
        firstName = inFirstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setLastName( String inLastName )
    {
        lastName = inLastName;
    }

    public long getPhone()
    {
        return phone;
    }

    public void setPhone( long inPhone )
    {
        phone = inPhone;
    }

    public long getMobNo()
    {
        return mobNo;
    }

    public void setMobNo( long inMobNo )
    {
        mobNo = inMobNo;
    }
}

And to search a Customer by its firstName and/or mobNo we can use Hibernate – Query by Example as:

Criteria criteria = session.createCriteria(Customer.class);
Customer customer=new Customer();
customer.setFirstName("Phoenix");
customer.setMobNo(9871234560);
criteria.add(Example.create(customer));
List<Customer> list = c2.list();

list will contain all the records matching the criteria.

You can also look for example code snippets at DZone – Hibernate Query by Example (QBE)

Advertisements