How to get Id of last persisted entity using JPA

后端 未结 1 750
慢半拍i
慢半拍i 2020-12-02 14:31

I am looking a smart and easily readable way to get the id of a persisted entity using JPA. The id is an Integer.

One could think of the fo

相关标签:
1条回答
  • 2020-12-02 15:21

    persist is not guaranteed to generate the ID. The ID is guaranteed to be generated at flush time only. So if you really need the ID before the transaction ends (and the entity manager is thus flushed), call flush() explicitely to get the ID:

    MyEntity en = new MyEntity();
    en.setName("My name");
    em.persist(en);
    em.flush();
    System.out.println(en.getId());
    
    0 讨论(0)
提交回复
热议问题