美好的一天! 我试图保存我的实体模型,但总是出现错误
Error inserting bean [class models.CategoryEntity] with unidirectional relationship. For inserts you must use cascade save on the master bean [class models.CategoryEntity].]
这是我的类(class)
@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
}
我尝试保存标题类别,但错误是相同的
最佳答案
如果我正确理解了这个问题,并且您想要的是每个 CategoryEntity 都包含其他 CategoryEntities 的列表,那么我会想到两种可能的方法(尽管它们都不使用 @OneToMany):
方法一:
您可以创建一个 @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 可以是多个 CategoryList 的一部分。每个 CategoryList 包含一个 CategoryEntities 列表。
您必须初始化 this_category_list 并将 CategoryEntities 添加到其category_list 字段。
关于java - Play框架中相同实体类的一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15591198/