JPA - Returning an auto generated id after persist()

前端 未结 7 1463
耶瑟儿~
耶瑟儿~ 2020-11-28 02:14

I\'m using JPA (EclipseLink) and Spring. Say I have a simple entity with an auto-generated ID:

@Entity
public class ABC implements Serializable {
     @Id
           


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 03:18

    The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:

    em.persist(abc);
    em.flush();
    return abc.getId();
    

    or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.

    @Override
    public ABC addNewABC(ABC abc) {
        abcDao.insertABC(abc);
        return abc;
    }
    

提交回复
热议问题