[英]javax.persistence.version causes the Id of an entity to remain null in the transaction
I have two entities with typical primary foreign key relationship. 我有两个具有典型主外键关系的实体。 id in EntityA is has foreign key relationship in EntityB. EntityA中的id在EntityB中具有外键关系。 I am trying to persist entity A and entity B in same transaction. 我试图将实体A和实体B保留在同一笔交易中。
Entity A
-------------------------------
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
@Version
private Integer version;
Entity B
--------------------------------
@ManyToOne
@JsonBackReference
@JoinColumn(name = "id_fk")
private EntityA entityA;
@Version
private Integer version;
I am using javax.persistence.version
annotation to perform the optimistic locking on version column. 我正在使用javax.persistence.version
批注对版本列执行乐观锁定。 I have two statements 我有两个陈述
1. entityARepository.save(entityA)
2. EntityB entityB = generateEntityB(entityA)
3. entityBRepository.save(entityB)
The statement number 3 fails with exception that entity A id is null and entityB can not be saved with id null of entity A. I tried to use entityManager.flush()
after statement 1 but the id of entity A is not getting generated when line 3 is encountered. 语句编号3失败,但例外情况是实体A的ID为null,而实体B的ID为null时,实体A不能保存。我试图在语句1之后使用entityManager.flush()
,但在行时未生成实体A的ID遇到3。
How to change the code so that Id of entity A gets generated and persisted so that when entityB tries to get that primary key of entity A it is not null
? 如何更改代码,以使实体A的ID生成并持久化,以便当EntityB尝试获取实体A的主键时,它不为null
?
If anyone is having the same issue the save operation of CrudRepository
of Spring Data
may return entirely different instance of entity so you will have to do following. 如果有人遇到相同的问题, Spring Data
的CrudRepository
的保存操作可能返回完全不同的实体实例,因此您必须执行以下操作。
1. entityA = entityARepository.save(entityA)
2. EntityB entityB = generateEntityB(entityA)
3. entityBRepository.save(entityB)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.