简体   繁体   中英

how to retrieve ID after object store into database

I am using Java, spring, jpa for our application. I want to retrieve Id of insert row. Basically our ID is generated at the time of storing object into database.

RoleRequest role = new RoleRequest();

roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(Enum.PENDING);

Dao.persist(roleRequest);

So after storing this object, I need new generated id for this object, so that will perform some operation on it.

Dao.persist(roleRequest);

After this line, the id should be set, so you can just do

Long id = roleRequest.getId();

(assuming id as id column and Long as id type)

What about:

oleRequest role = new RoleRequest();

roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(RoleRequestStatusEnum.PENDING);

Dao.persist(roleRequest);
int myId = roleRequest.getId();

You may need to do EntityManager.flush() after EntityManager.persist() (YMMV).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM