我在使用hibernate的一对多映射中遇到一个问题。
我有2个班级,人和地址。人通过地址(一对多)映射 我想得到所有地址=“xxxx”;的人。如何使用 DetachedCriteria 准备此查询。下面我添加了一段来自我的dao类的代码。请帮我完成它。
Person.java
@Entity
@Table(name="PERSON")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="personId")
private int id;
@Column(name="personName")
private String name;
@OneToMany(cascade =CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name="personId")
private Set <Address> addresses;
}
Address.java
@Entity
@Table(name = "ADDRESS")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "addressId")
private int id;
@Column(name = "address",nullable=false)
private String address;
@ManyToOne(cascade =CascadeType.ALL)
@JoinColumn(name="personId",nullable=false)
private Person person;
}
我的DAO
DetachedCriteria c = DetachedCriteria.forClass(Person.class);
List<Person> persnList =null;
/*here i want add some restriction for
fetch all person whose address = "abcd"
here address is collection. how to set restriction in it ?.
*/
persnList = getHibernateTemplate().findByCriteria(c);
System.out.println(persnList.size());
从人员中选择*,其中Address.address =“xxxx”; 如何使用 DetachedCriteria 实现此目的?
答案 0 :(得分:1)
DetachedCriteria c = DetachedCriteria.forClass(Person.class);
List<Person> persnList =null;
DetachedCriteria addrCrit = c.createCriteria("addresses").addRestriction(Restrictions.eq("address","abcd"));
addrCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
persnList = getHibernateTemplate().findByCriteria(c);
System.out.println(persnList.size());
在主要标准上创建内部标准,这些标准将执行等效的内部联接。