如何在外部实体中执行join

时间:2015-10-09 11:30:31

标签: hibernate

我正在与两个实体合作 - TopPackageTop如下所示。

@Entity
@Table(name = "top_top")
public class Top implements Serializable {

    private int id;
    private Package pkg;
    private int package_ref;

    @Id
    @Column(name="id", unique=true)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "package_ref", insertable=false, updatable=false)
    public Package getPackage() {
        return pkg;
    }

    public void setPackage(Package pkg) {
        this.pkg = pkg;
    }

}

Package如下所示:

@Entity
@Table(name = "package_package")
public class Package implements Serializable {

    private int id;
    private Integer parent_id;
    private Package parent;


    @Id
    @Column(name="id", unique=true)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "parent_id")
    public Package getParent() {
        return parent;
    }
    public void setParent(Package parent) {
        this.parent = parent;
    }
}

鉴于Top a ,我想要Top的父级为 a 的所有Package的列表。封装

为此,我尝试了

private List<Top> getSubTops(Top pkg_top) {
    return getSession().createCriteria(Top.class).add(Restrictions.eq("package.parent.id", pkg_topo.getPackage().getId())).list();// Throws an error
   // "tried package.parent_id". That throws an error too.
   // In Django - I would have done Package.objects.filter(package__parent=a.package)
}

1 个答案:

答案 0 :(得分:1)

试试这个:

private List<Top> getSubTops(Top pkg_top) {
    return getSession().createCriteria(Top.class)
        .createCriteria("package")
            .add(Restrictions.eq("parent", pkg_top.getPackage()).list();
}