我有一个简单的父子关系。
问题:在我的数据库中,有时会有多个子元素映射到同一个父元素。
@Entity
public class PersonEntity {
@Id
private long id;
//assume every person can only have one car
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
private CarEntity car;
private String name;
}
@Entity
public class CarEntity {
@Id
private long id;
@OneToOne
@JoinColumn(name = "fk_person_id", foreignkey = @ForeignKey("name = "fk_person"))
private PersonEntity person;
private String name;
}
问题:如果有多个car
元素映射到相同的人员实体,我怎么会发生? hibernate如何能够持久保存这些元素?他们在哪里可以来自?
因此,当我获取具有多个汽车映射的人员实体时,我当然是个例外:
Caused by: org.hibernate.HibernateException: More than one row with the given identifier was found: 123, for class: CarEntity...
旁注:我最终想要删除重复的CarEntity
并且只保留最新的@Transactional
public PersonEntity createUpdatePerson(PersonDTO dto) {
PersonEntity entity = dao.findByPersonName(dto.getName); //CrudRepository by spring
if (entity == null) {
entity = new Person();
}
mergeDTO(dto, entity); //copy and fill new values
if (person.getId() == null) dao.save(entity);
return entity;
}
private void mergeDTO(PersonDTO dto, PersonEntity entity) {
if (dto.getCar() != null) {
if (entity.getCar() == null) entity.setCar(new Car());
entity.getCar().setName(dto.getCar().getName());
entity.getCar().setPerson(entity);
}
}
。但是我怎么能阻止将来发生这种情况呢?
更新
var foo = ...// some function assignment
var fooString = foo.toString()
...
// add some alert to foo
...
var fooWithAlert = new Function(forStringWithAlert)