How to get the last inserted keys without using operators or "LAST_INSERTED_ID"

I am looking for a way to get the latest generated keys / identifiers from an insert made through "createNativeQuery", similar to "getGeneratedKeys" in PreparedStatement.

As I wrote in the first paragraph, I know that it is possible to use PreparedStatement, which really works, and we use it for some different cases. I also know that I can make a direct selection in the database and call "LAST_INSERT_ID" or "@@ Identity", which also works, but this is the way I want to avoid. At the moment, I am using row inserts in the database, and then I called a simple "LAST_INSERT_ID ()" and retrieved the identifier.

I want to avoid this because it works until I started testing ProxySQL, which I think is doing some things with connections / sessions, and when I call LAST_INSERT I just get a null value (but when I try to do the same with Prepared statements and getGeneratedKeys, it works)

There are dozens of similar stack themes, such as this , but I have not found a single answer.

I played with the getResultList and getLastResult Query methods, but nothing leads to a successful way to get the latest generated identifiers.

+5
source share
1 answer

Using JPA, an identifier is generated only during cleanup. Therefore, if you need the flush () call id to get the id:

Entity en = new Entity(); en.setName("My Entity name"); em.persist(en); em.flush(); System.out.println(en.getId()); 
0
source

Source: https://habr.com/ru/post/1269470/


All Articles