Hibernate query a foreign key field with ID

北战南征 提交于 2019-12-02 17:53:55
ChssPly76

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));

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!