简体   繁体   English

object 存储到数据库后如何检索 ID

[英]how to retrieve ID after object store into database

I am using Java, spring, jpa for our application.我正在为我们的应用程序使用 Java、spring、jpa。 I want to retrieve Id of insert row.我想检索插入行的 ID。 Basically our ID is generated at the time of storing object into database.基本上,我们的 ID 是在将 object 存储到数据库时生成的。

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.所以在存储了这个 object 之后,我需要为这个 object 生成新的 id,以便对其执行一些操作。

Dao.persist(roleRequest);

After this line, the id should be set, so you can just do在这一行之后,应该设置 id,所以你可以这样做

Long id = roleRequest.getId();

(assuming id as id column and Long as id type) (假设id为 id 列, Long为 id 类型)

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).您可能需要在EntityManager.persist() (YMMV) 之后执行EntityManager.flush() ()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在SQLite数据库中存储和检索ApplicationInfo对象? - How to Store and retrieve ApplicationInfo object in SQLite database? 如何从 SQlite 数据库中的可绘制对象存储 ID 并再次检索它? - How to store ID from a drawable in SQlite database and retrieve it again? 如何在jComboBox中检索绑定到数据库表中的对象并将其存储到另一个表 - How to retrieve the object in jComboBox that is binded in database table and store it to another table 存储和检索布尔对象到MySql数据库 - Store and retrieve Boolean Object to a MySql database 通过Firebase数据库按ID检索对象 - Retrieve object by id from database of Firebase 如何检索数据库值并将其存储为树数据结构? - How to retrieve database value and store it for a tree datastructure? 如何从房间数据库中存储和检索图像 - How to store and retrieve image from room database 如何在数据库postgresql中存储secretKey并检索它 - How to store a secretKey in database postgresql and retrieve it 如何在Java中的日期对象中存储和检索毫秒? - How to store and retrieve milliseconds in a date object in Java? 如何在 SharedPreferences 中存储和检索 Location 对象? - How to store and retrieve Location object in SharedPreferences?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM