davioooh
davioooh

Reputation: 24676

Get generated id for related JPA entity

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

Is there a way to achieve this?

Upvotes: 0

Views: 1596

Answers (3)

Lesiak
Lesiak

Reputation: 25966

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.

Upvotes: 1

grange
grange

Reputation: 657

paymentRepository.save(payment)

should return the saved instance payment.

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

Upvotes: 0

tbjorch
tbjorch

Reputation: 1758

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.

Upvotes: 1

Related Questions