Hibernate Annotations self referencing class?

2019-08-14 15:51发布

问题:

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

回答1:

That's because the reverse association is never persisted; I can tell this is the reverse association beacause of the "mappedBy" attribute



回答2:

Add this method to your class:

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

Also make sure you initialize the children list either inline or inside the constructor:

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

Then try this:

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

It should work now.