JPA - Returning an auto generated id after persist()

前端 未结 7 1423
耶瑟儿~
耶瑟儿~ 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 02:55
    em.persist(abc);
    em.refresh(abc);
    return abc;
    
    0 讨论(0)
  • 2020-11-28 02:58

    You could also use GenerationType.TABLE instead of IDENTITY which is only available after the insert.

    0 讨论(0)
  • 2020-11-28 03:05

    Another option compatible to 4.0:

    Before committing the changes, you can recover the new CayenneDataObject object(s) from the collection associated to the context, like this:

    CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();
    

    then access the ObjectId for each one in the collection, like:

    ObjectId objectId = dataObject.getObjectId();
    

    Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot(), it contains also the column name(s) associated to the PK as key(s):

    objectId.getIdSnapshot().values()
    
    0 讨论(0)
  • 2020-11-28 03:09

    This is how I did it. You can try

        public class ABCService {
        @Resource(name="ABCDao")
        ABCDao abcDao;
    
        public int addNewABC(ABC abc) {
             ABC.setId(0);
             return abcDao.insertABC(abc);
        }
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-28 03:18

    This is how I did it:

    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    entityManager.persist(object);
    transaction.commit();
    long id = object.getId();
    entityManager.close();
    
    0 讨论(0)
提交回复
热议问题