Hibernate Query - 不是另一个实体的子实体的实体

时间:2016-09-15 10:47:24

标签: hibernate criteria psql

我有一个实体的递归结构:实体Goal有一个属性subgoals,它是Goal个实体本身的列表。

@Entity
@Table( name = "GOAL" )
public class Goal {
    ...
    @OneToMany
    @JoinTable(name = "goal_subgoals")
    private List<Goal> subgoals = new ArrayList<Goal>();
    ...
}   

现在我需要一个查询来所有 Goal个实体 subgoal任何Goal

由于有一个联接表goal_subgoals,列goal_idsubgoals_id,我可能需要的是id不在subgoals_id的所有目标该表的列。有关如何做到这一点的任何建议吗?

我知道如何获得作为子目标的所有目标:

Query query = session.createQuery(
            "SELECT subgoalx "
                    +" FROM Goal goalx "
                    + "JOIN goalx.subgoals subgoalx "                       
            );

有没有办法获得该套装的补充?

1 个答案:

答案 0 :(得分:0)

这对我有用

    DetachedCriteria subQuery = DetachedCriteria.forClass(Goal.class,"goalx")
            .createAlias("goalx.subgoals", "subgoalsx")
            .setProjection(Projections.property("subgoalsx.id"));

    Criteria query = session.createCriteria(Goal.class)
            .add(Subqueries.propertyNotIn("id",subQuery));