保存父实体时子实体未持久化

时间:2021-06-10 16:08:47

标签: java spring-data-jpa one-to-one

我有两个具有一对一关系的实体。

它们如下,

@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);

}

}

当我第一次创建新的子实体时,此代码有效。但是当更新子实体时,它没有得到更新。

如果我遗漏了什么,请告诉我。

2 个答案:

答案 0 :(得分:0)

我猜你的问题与这条线有关。

@JoinColumn(name = "id", insertable = false, updatable = false)
private Parent parent;

我的意思是 insertable = falseupdatable = false。 当可更新和可插入等于 false 时,我认为它不会更新。

答案 1 :(得分:0)

您必须进行双向设置。 在 p.setChild(c) 之后添加以下行。

C.setParent(p)