【问题标题】:one to many for same entity class in play framework游戏框架中同一实体类的一对多
【发布时间】:2013-03-23 19:35:42
【问题描述】:

美好的一天! 我试图通过总是出错来保存我的实体模型

Error inserting bean [class models.CategoryEntity] with unidirectional relationship. For inserts you must use cascade save on the master bean [class models.CategoryEntity].]

这是我的课

@Entity
public class CategoryEntity extends Model {
    @Id
    private String categoryId;

    private String Name;
    private Integer level;

    @OneToMany(targetEntity = CategoryEntity.class, cascade = CascadeType.ALL)
    private List<CategoryEntity> categories;
//GETERS SETRES
}

我试图保存标题类别,但错误是一样的

【问题讨论】:

    标签: java playframework playframework-2.0 playframework-2.1 ebean


    【解决方案1】:

    如果我正确理解了这个问题并且您想要的是每个 CategoryEntity 包含其他 CategoryEntities 的列表,那么会想到 2 种可能的方法(尽管它们都没有使用 @OneToMany):

    方法 1:
    您可以创建一个@ManyToMany 关系并定义一个@JoinTable,同时命名它的键:

    @Entity
    public class CategoryEntity extends Model {
        @Id
        private String categoryId;
    
        private String name;
        private Integer level;
    
        @ManyToMany(cascade=CascadeType.ALL)
        @JoinTable(         name = "category_category",
                     joinColumns = @JoinColumn(name = "source_category_id"), 
              inverseJoinColumns = @JoinColumn(name = "target_category_id"))
        public List<CategoryEntity> category_entity_lists = new ArrayList<CategoryEntity>();
    }
    



    方法 2:
    或者您可以为类别实体列表创建一个新实体并创建@ManyToMany 关系,例如:

    @Entity
    public class CategoryList extends Model
    {
        @Id
        public Long id;
    
        @ManyToMany
        @JoinTable(name="categorylist_category")
        public List<CategoryEntity> category_list = new ArrayList<CategoryEntity>();
    }
    

    然后在你的模型中:

    @Entity
    public class CategoryEntity extends Model {
        @Id
        private String categoryId;
    
        private String name;
        private Integer level;
    
        @OneToOne
        public CategoryList this_category_list;
    
        @ManyToMany(mappedBy="category_list")
        public List<CategoryList> in_other_category_lists = new ArrayList<CategoryList>();
    }
    

    没有测试代码,但这应该做的是每个 CategoryEntity 可以是几个 CategoryLists 的一部分。每个 CategoryList 都包含一个 CategoryEntities 列表。

    您必须初始化 this_category_list 并将 CategoryEntities 添加到其 category_list 字段。

    【讨论】:

    • @nabiullinas 你用哪种方法成功了?
    【解决方案2】:

    您的模型没有意义。 为什么你将类本身作为类属性?

    列表不应属于同一类

    【讨论】:

    • 为什么不呢?个人实体可以有朋友,其他人
    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多