Hibernate query a foreign key field with ID
Asked Answered
E

2

41

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?

Eph answered 24/11, 2009 at 0:40 Comment(2)
I have to ask: why does Employee have an ID field for the address? Can an employee not have more than one address? Wouldn't it make more sense for the Address object have an ID field for the employee? In the end, what's more likely -- an employee having more than one address, or an address having more than one employee? If it's the former, than you have your foreign-key relationship reversed...Catiline
Thanks delfuego for the comment. This is just a quick example I came up with to show the problem. For real production system, I agree the relationship could be more complicated. There probably will be an association table.Eph
G
77

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));
Gangway answered 24/11, 2009 at 1:2 Comment(0)
B
5

Having similar trouble... @ChssPly76 answer works fine, but just found solution if foreign key is not part of Id in parent table - you must modify annotation by adding "referencedColumnName":

@ManyToOne
@JoinColumn(name="address_id", referencedColumnName="addrUniqueFieldName")
private Address address;

and then you can create criteria:

criteria.add(restriction.eq("address.addrUniqueFieldName", 123);
Beauregard answered 22/7, 2014 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.