[英]Child entity not getting persisted when saving parent entity
I have two entities with one-to-one relationships.我有两个具有一对一关系的实体。
They are as follows,它们如下,
@Entity
class Parent {
@Id
private String id;
@OneToOne(mappedBy = "parent", cascade = CascadeType.ALL)
private Child child;
// getter setter
}
@Entity
public class Child {
@Id
private String id;
@OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name = "id", insertable = false, updatable = false)
private Parent parent;
// getter setter
}
@Service
public TestService {
@Autowired
private ParentRepository parentRepository;
public void testMethod() {
// Creating new ChildElement
Parent p = parentRepository.findById("ID1").get();
Child c = parent.getChild()
if(c == null) {
c = new Child()
c.setId("ID2");
}
// set child with some property
p.setChild(c);
parentRepository.save(p);
}
}
This code is working when I am creating a new child entity for the first time.当我第一次创建新的子实体时,此代码正在工作。 But when updating the child entity, it is not getting updated.但是在更新子实体时,它没有得到更新。
Could you please let me know if I am missing something.如果我遗漏了什么,请告诉我。
I guess your problem is related to this line.我猜你的问题与这条线有关。
@JoinColumn(name = "id", insertable = false, updatable = false)
private Parent parent;
I mean insertable = false
and updatable = false
.我的意思是insertable = false
和updatable = false
。 When updatable and insertable are equal false it won't be updated I think.当可更新和可插入相等时,我认为它不会被更新。
You have to do bidirectional setting.您必须进行双向设置。 Add below line after p.setChild(c).在 p.setChild(c) 之后添加以下行。
C.setParent(p)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.