0

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?

somename
  • 978
  • 11
  • 30
  • If you are saving 2 entities then kindly POST the entities (JPA is orientated around CLASSES, not TABLES), and the code to interrelate the objects, and then post the actual SQL invoked – Neil Stockton Aug 31 '17 at 18:05
  • see the updated question. Thanks! – somename Aug 31 '17 at 18:18
  • Are you using JPA? then you use an Entitymanager, I presume. The save-method does a call to entitymanager.persist? I deleted my first question – aschoerk Aug 31 '17 at 18:53
  • I am using CrudRepository of spring data so save is same as persist. I found the problem I needed to get the new object that gets returned from line 1 and then save it in line 2. Apparently save operation changes the entity instance. – somename Aug 31 '17 at 19:17
  • a works as entitymanager.merge. ok – aschoerk Aug 31 '17 at 19:47

1 Answers1

1

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.

   1. entityA = entityARepository.save(entityA)
   2. EntityB entityB = generateEntityB(entityA)
   3. entityBRepository.save(entityB)
somename
  • 978
  • 11
  • 30