1

I have defined this Entity class, but it does not seem to save the children to the database. Any ideas?

@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;
    }

}

Many thanks, Finbarr

4

2 回答 2

4

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

于 2011-03-16T17:15:05.683 回答
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());
}

它现在应该可以工作了。

于 2011-03-17T06:39:46.367 回答