0

我在使用休眠的一对多映射中遇到了一个问题。

我有 2 个班级,PersonAddress。人员由地址映射(一对多)我想获取地址 =“xxxx”的所有人员;。如何使用DetachedCriteria准备此查询。下面我从我的 dao 类中添加了一段代码。请帮我完成它。

人.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;
}

地址.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());

select * from person where Address.address = "xxxx"; 如何使用DetachedCriteria实现这一点 ?

4

1 回答 1

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

在将执行等效内部连接的主要标准上创建内部标准。

于 2011-11-28T13:32:06.157 回答