我有两个表(类别和子类别)
这是我的分类模型
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int mCat_Id;
@Column(name = "category" , unique = true)
@JsonProperty("category")
private String mCategory;
}
public class SubCategory {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int mSub_Cat_Id;
@Column(name = "subcategory")
@JsonProperty("subcategory")
private String mSubCategory;
@OneToMany
@JoinColumn(name="category_id")
private Category category;
}
并输入
record 1:
{"subcategory":"ss" , "category":{ "category":"upsc"}}
record 2:
{"subcategory":"science" , "category":{ "category":"upsc"}}
每当我传递不同的子类别并且类别保持不变时,它就会将upsc添加为新记录。
我的要求是:当我传递类似的类别时,它不应该在类别表中创建记录。
我错过了什么吗?或者有没有其他方法来实现这一目标?
预期结果:
Category table > 1 record > category : upsc , category_Id : 1
SubCategory table > 2 records >
subcategoty : science , category_Id : 1 , subcategory_id : 1
subcategoty : ss, category_Id : 1 , subcategory_id : 2
答案 0 :(得分:0)
为什么你有OneToOne关系?看到你提供的输入应该如下所示。
Entity
@Table(name = "sub_category")
public class SubCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "subcategory_id")
private int subCategoryId;
@Column(name = "subcategory")
private String subCategory;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
}
你的分类类似于我的吗?
Entity
@Table(name = "category")
public class Category{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "category_id")
private int categoryId;
@Column(name = "category")
private String category;
}
现在不应该向Category类添加新记录。
您还必须删除CascadeType.ALL
,它指示Hibernate保存所有关联。