【问题标题】:Hibernate Annotations self referencing class?Hibernate Annotations 自引用类?
【发布时间】:2011-03-16 17:11:54
【问题描述】:

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

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

}

非常感谢, 芬巴尔

【问题讨论】:

    标签: hibernate jpa entitymanager


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      将此方法添加到您的类中:

      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-02-03
        • 2012-06-10
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多