Home > Enterprise >  Get generated id for related JPA entity
Get generated id for related JPA entity

Time:04-06

In my project I have something like this:

@Entity
public class Refund {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @ManyToOne(fetch = FetchType.LAZY)
    private Payment payment;

    // ... other fields...
}

@Entity
public class Payment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "payment")
    private List<Refund> refunds;
    
    // ... other fields...
}

Payment is the aggregate root and when I need to add a new Refund I use this logic:

Payment payment = // fetch or create a Payment
    

Refund refund = // create   populate new Refund
refund.setPayment(payment);

payment.getRefunds().add(refund);
paymentRepository.save(payment); // <= here I'm using a Spring Data JPA repository

After saving payment I'd like to retrieve the id of the newly created Refund, but the id field is not populated in refund instance.

NOTES

  • The method implementing the save logic is annotated with @Transactional.
  • I also tried to use repo saveAndFlush method but nothing changes...

Is there a way to achieve this?

CodePudding user response:

You need to make sure to update the payment object upon the call to the save method. What you need to do is to update to the following:

payment = paymentRepository.save(payment);

After this, you should be able to see the IDs set, etc.

CodePudding user response:

paymentRepository.save(payment)

should return the saved instance payment.

From there you can access your refunds and get the id.

CodePudding user response:

The id is available on the value returned from save. In your case, the merge operation is cascaded to the collection of Refunds, and the updated refund will be available in the collection from returned payment.

Having said that, if your goal is only to add a Refund to the DB, you may prefer to save the Refund instead - it is the owning side of the relation.

See javadoc for CrudRepository.save

<S extends T> S save(S entity)

Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.

  • Related