简体   繁体   English

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

[英]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 = falseupdatable = 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.

相关问题 当持久保存新的子实体时,父实体会不必要地更新 - Parent entity getting unnecessarily updated when a new child entity is persisted 保存“子”实体时如何持久保存“父”实体? - How to persist “parent” entity when saving a “child” entity? 在父实体被持久化并被选中之后,子实体为空 - Child entity is null after parent entity is persisted and selected JPA OneToOne 关系在保存父实体时不会保留子实体 - JPA OneToOne relation doesnt persist child entity when saving parent 保存单向一对一子实体时分离的永久父实体 - Detached persited parent entity when saving unidirectional one-to-one child entity 当从集合中删除父实体并保存父实体时,处理EntityNotFoundException - Handle EntityNotFoundException when saving parent entity with removed child entity from collection 更新子实体但保存父实体会导致ObjectOptimisticLockingFailureException - Updating child entity but saving parent entity leads to ObjectOptimisticLockingFailureException 实体对象持续存在时,出现空指针异常 - Null Pointer exception when entity object is getting Persisted OneToOne 映射在选择父实体时未获取子实体 - OneToOne mapping not getting child entity while selecting parent entity 休眠:保存子实体 - Hibernate :saving child entity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM