Hibernate query a foreign key field with ID

savanna picture savanna · Nov 24, 2009 · Viewed 42k times · Source

For example, I have two entities: Employee and Address. Of these enitities, Employee has a foreign key AddressID references the ID column on Address. In the Java domain objects, Hibernate nicely wraps the forgein key integer field with a Address object field. But now, how could I query the Employee with a certain AddressID?

I have tried to create a table alias. That seems to work, but it is fairly awkward.

I had also tried to do something like this:

criteria.add(restriction.eq("TheAddressObjectFieldName", 123);

It works some time but not always. I am not sure this is the right way, but I was hoping it could all the time.

So what is the right way to query on a foreign key column in hibernate?

Answer

ChssPly76 picture ChssPly76 · Nov 24, 2009

Hibernate "nicely wraps" only what you tell it to wrap. So, assuming that your Employee mapping looks something like:

@Entity
public class Employee {
  ...
  @ManyToOne
  @JoinColumn(name="address_id")
  private Address address;
  ...
}

and your Address has an id property, you can query based on address_id via:

session.createCriteria(Employee.class)
 .add(Restrictions.eq("address.id", addressId));

In order to query based on Address properties, you'll have to create aliases or nested criteria:

session.createCriteria(Employee.class)
 .createAlias("address", "a")
 .add(Restrictions.eq("a.postalCode", postalCode));