开发者

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜