OPK
OPK

Reputation: 4180

Hibernate implementation by pass in different types of params

So I am able to get Company information by passing in Company ID with Hibernate, code is as follows:

public Company getCompanyById(Integer companyId) {
    Company company = (Company) getCurrentSession().get(Company.class, companyId);
    return company;
}

Now what I am trying to do is to pass in company name, address and cell phone number to get the company. The method in my mind is like this:

 public Company getCompanyByNameAddressCellphone(String companyName, String address, Integer cellPhoneNumber);

How do I implement it?

Upvotes: 1

Views: 60

Answers (2)

Jeff
Jeff

Reputation: 3707

You can either use Criteria/DetachedCriteria or HQL. A Criteria instance or a Query instance can both be retrieved from the session (referenced by the same getCurrentSession() call in your example).

Not sure what version of Hibernate you're working with, but here is the documentation on querying: https://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/objectstate.html#objectstate-querying

the key points are that your property names (Company.name, Company.address, etc.) are used to query rather than the DB column names, which your code shouldn't be expected to know.

My personal preference is for DetachedCriteria. Used with the Restrictions API, you can accomplish about 85% of your querying needs. DetachedCriteria's execution flow is slightly different and documented here: https://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/querycriteria.html#querycriteria-detachedqueries

Upvotes: 1

Default
Default

Reputation: 16488

You can use Hibernate Criteria to achieve this. It would look something like:

public Company getCompanyByNameAddressCellphone(String companyName, String address, Integer cellPhoneNumber) {
    Criteria criteria = getCurrentSession().createCriteria(Company.class);
    criteria.add(Restrictions.eq("companyName", companyName));
    criteria.add(Restrictions.eq("address", address));
    criteria.add(Restrictions.eq("cellPhoneNumber", cellPhoneNumber));
    return criteria.uniqueResult();
}

In this scenario, the String values provided to the Restrictions#eq call are the property names of your Company entity.

If you don't want to match exact String values and prefer using like, you can use Restrictions#like or Restrictions#ilike (case insensitive version).

Upvotes: 1

Related Questions