Hibernate使用ID查询外键字段 [英] Hibernate query a foreign key field with ID

查看:518
本文介绍了Hibernate使用ID查询外键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个实体:员工和地址。在这些实体中,Employee有一个外键AddressID引用Address上的ID列。在Java域对象中,Hibernate用Address对象域很好地包装了伪造关键字整数字段。但是现在,我怎么能用某个AddressID查询Employee?

我试图创建一个表别名。这似乎工作,但它相当尴尬。



我也尝试过这样做:

 标准.add(restriction.eq(TheAddressObjectFieldName,123); 

它有点时间但并不总是。我不确定这是正确的方式,但我一直希望它可以。



那么什么是正确的方式来查询外键列hibernate?

解决方案

Hibernate很好地包装了你所要包装的东西,所以假设你的 Employee 映射看起来像这样:

  @Entity 
public class Employee {
...
@ManyToOne
@JoinColumn(name =address_id)
私人地址;
...
}

和您的地址有一个 id code> property,你可以通过 address_id 来查询:

  session.createCriteria(Employee.class)
.add(Restrictions.eq(a ddress.id,addressId));

为了基于 Address 属性进行查询,您必须创建别名或嵌套标准

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


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?

解决方案

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

这篇关于Hibernate使用ID查询外键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆