1

I am using Spring Data JPA + Hibernate. I need to get ID of entity after it's added to a list of other entity and saved. Here is the code:

@Entity
public class Product extends AbstractAuditable<Long> {


    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", nullable = false)
    private List<Feedback> feedbacks = new ArrayList<Feedback>();

    ...

}


@Entity
public class Feedback extends AbstractPersistable<Long> {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", insertable = false, updatable = false, nullable = false)
    private Product product;

    ...

}


public interface ProductRepository extends JpaRepository<Product, Long> {

}


Feedback feedback = new Feedback();
product.getFeedbacks().add(feedback);
productRepository.saveProduct(product);
feedback.getId(); // returns null

How to correctly get ID of feedback after it's saved?

igo
  • 6,359
  • 6
  • 42
  • 51

1 Answers1

0

You can execute refresh method from Hibernate Session interface (or EntityManager interface) to "re-read the state from the given instance from the underlying database". Example:

session.save(object);
session.flush();
session.refresh(object);

You can find more information here:

Community
  • 1
  • 1
Aneta Stępień
  • 704
  • 6
  • 20