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 t开发者_开发知识库ime 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).
精彩评论