【发布时间】:2020-06-26 08:59:06
【问题描述】:
我创建了一个子实体:
public class ChildEntity {
private Long bookNo;
private String bookType;
}
这两个字段一起是唯一的。某种数据:
| No | Type |
|----|-----------|
| 1 | Classical |
| 2 | Classical |
| 2 | Scifi |
| 3 | Scifi |
| 1 | Classical | (Error for uniqueness
我创建了这个实体来搜索父实体。
public class ParentEntity{
@ManyToOne
private ChildEntity child;
//and other fields here
}
此外,还有 2 个不同的父实体。他们必须是不同的实体,他们有几个不同的领域。但是这个子实体很常见。因此,我将使用这些子实体来比较/获取数据表之间的差异,因为该子实体中只有唯一区域。我可以通过该子实体字段获取数据表的差异。
我制作了 ManyToOne,因为许多不同的父母可以拥有同一个孩子。
我在这样的服务中创建父实体:
private createParentEntity(Dto dto){
ParentEntity parent = new ParentEntity();
//set other fields from dto
parent.setAge(dto.getAge);
ChildEntity child = new ChildEntity();
child.setBookNo(dto.getBookNo());
child.setBookType(dto.getBookType());
parent.setChild(child);//here is problem , please look down
}
我的问题是,我发表评论的那一行。
相同的子实体可以来,所以当我保存父母时,它会再次尝试保存孩子并且会得到一个唯一的约束错误?我该怎么做?
因为最后我会使用spring data在父仓库里面这样搜索:
parentEntityRepository.findByChild(ChildEntity child);
@UniqueConstraints = {
@UniqueConstraint(
name = "uq_general_checklist_ordinal",
columnNames = {"book_no", "book_type"}
)
}
public class ChildEntity {
@Id
private Long bookNo;
@Id
private String bookType;
}
放置两个 ID 是否是一个好的解决方案?还是这里,我应该先救下孩子,看看它是否存在?
ChildEntity child =childRepository.findByBookNoAndBookType(
dto.getBookNo(),
dto.getBookType()
);//if exists, set to parent. if not, create new and set it?
【问题讨论】:
标签: java spring-boot spring-data unique-constraint spring-repositories