Hibernate Annotations自引用类?

时间:2011-03-16 17:11:55

标签: hibernate jpa entitymanager

我已经定义了这个Entity类,但它似乎没有将子节点保存到数据库中。有任何想法吗?

@Entity
public class CategoryModel implements Model<CategoryModel>, Serializable {

    private static final long serialVersionUID = -4520507504770029807L;

    @Id
    @Field(index = Index.UN_TOKENIZED, store = Store.NO)
    private String id;

    @NotNull
    private String name;

    @ManyToOne
    private CategoryModel parent;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
    private List<CategoryModel> children;

    public List<CategoryModel> getChildren() {
        return children;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public CategoryModel getParent() {
        return parent;
    }

    public void setChildren(List<CategoryModel> children) {
        this.children = children;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public void setParent(CategoryModel parent) {
        this.parent = parent;
    }

}

非常感谢, 财务巴雷

2 个答案:

答案 0 :(得分:4)

那是因为反向关联永远不会持续存在;我可以说这是因为“mappedBy”属性

的反向关联

答案 1 :(得分:3)

将此方法添加到您的班级:

public void addChild(CategoryModel child) {
  child.setParent(this);
  getChildren().add(child);
}

还要确保在内联或构造函数内部初始化children列表:

private List<CategoryModel> children = new ArrayList<CategoryModel>();

然后试试这个:

CategoryModel parent = new CategoryModel();
for (int i = 0; i < 10; i++) {
 parent.addChild(new CategoryModel());
}

现在应该可以了。