使用Criteria API选择没有父Hibernate的记录

时间:2016-05-12 09:42:51

标签: java sql hibernate orm annotations

如何使用Criteria API选择没有父Hibernate的记录?

这是我用父母选择的Java代码

getSessionFactory().getCurrentSession().createCriteria(Category.class).add(
Restrictions.eq("parent", new Category(parentId))).list();

类别Java代码

@Entity
@Table(name = "CATEGORY")
public class Category implements NamedModel{
    @Id
    @Column(name = "CATEGORY_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
    @JoinTable(name = "CATEGORY_RELATIONS",
        joinColumns = {
                @JoinColumn(name = "CATEGORY_RELATIONS_CATEGORY_ID", referencedColumnName = "CATEGORY_ID")},
        inverseJoinColumns = {
                @JoinColumn(name = "CATEGORY_RELATIONS_PARENT_ID", referencedColumnName = "CATEGORY_ID")})
    private Category parent;
    @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "parent")
    private List<Category> children;//...
}

CategoryRelations Java代码

@Entity
@Table(name = "CATEGORY_RELATIONS")
@IdClass(CategoryRelations.CategoryRelationsPrimaryKey.class)
public class CategoryRelations implements Serializable {
    @Id
    @Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
    private long categoryId;
    @Id
    @Column(name = "CATEGORY_RELATIONS_PARENT_ID")
    private long parentId;

    @Entity
    @IdClass(CategoryRelationsPrimaryKey.class)
    public static class CategoryRelationsPrimaryKey implements Serializable    {
        private long categoryId;
        private long parentId;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以根据自己的要求使用Restriction#isNull(propertyName)功能。

Restrictions.isNull("parent")