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<CategoryM开发者_运维知识库odel>, 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
That's because the reverse association is never persisted; I can tell this is the reverse association beacause of the "mappedBy" attribute
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.
精彩评论