I have two entities with typical primary foreign key relationship. id in EntityA is has foreign key relationship in EntityB. I am trying to persist entity A and entity B in same transaction.
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. 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.
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
?
If anyone is having the same issue the save operation of
CrudRepository
ofSpring Data
may return entirely different instance of entity so you will have to do following.