1

I'm looking for a way how to retrieve last generated keys/ids from insert performed via "createNativeQuery" in similar way like "getGeneratedKeys" in PreparedStatement.

As I wrote in first paragraph, I know there is a possibility to use PreparedStatement which actually works and we are using it for some different cases. Also I know that I can do direct select into database and call "LAST_INSERT_ID" or "@@Identity" which also works, but that's a way I want to avoid. For now I've been using inserting rows into DB and then I was calling simple "LAST_INSERT_ID()" and retrieve the id.

I want to avoid this because it works until I started to testing ProxySQL, which, I guess, do some stuff with connections/sessions and when I call LAST_INSERT I will just get zero value (but when I try the same with Prepared statements and getGeneratedKeys, it works)

There are dozens of similar stack topics like this, but I didn't find a single answer.

I've been playing around with getResultList and getLastResult Query methods, but nothing leads to a success way how to retrieve last generated ids.

Radim
  • 164
  • 1
  • 4
  • 18
  • 1
    _“but that's a way I want to avoid for some reason”_ – unless you explain that reason, I consider this question incomplete. (Who knows whether the alternative solution they might suggest would not also not match your “reason” ... so trying to answer would be rather pointless.) – CBroe Jul 04 '17 at 08:41
  • I've edited a question a little bit and also added a reason. – Radim Jul 04 '17 at 08:45

1 Answers1

0

Using JPA the ID is generated at flush time only. So if you need the ID call flush() to get the ID:

Entity en = new Entity();
en.setName("My Entity name");
em.persist(en);
em.flush();
System.out.println(en.getId());
Iffo
  • 353
  • 7
  • 18
  • Thank you for your response, but unfortunately it's not that simple. We're using some native insert, where we specify exactly what columns are inserted in which table. So we not want to do it this way – Radim Jul 07 '17 at 06:36