I have an existing implementation which uses MySql 5.7.36 (Percona), Java MySql Connector 8.0.31 and Hibernate 5.6.12 with c3p0. Application is written in Kotlin and is running multiple threads.
Part of the implementation uses additional layer, which then uses native queries using javax.persistence.EntityManager.createNativeQuery. This layer has a method, that returns id of last inserted entry (simplified code):
fun lastInsertId(entityManager) {
val query = entityManager.createNativeQuery("LAST_INSERT_ID()")
return (query.resultList as List<Long>).first()
}
And that is then used like this (simplified code):
val query = entityManager.createNativeQuery(queryString)
query.setParameter(0, parameter)
affectedRows = query.executeUpdate()
lastInsertId = lastInsertId(entityManager)
This solution usually works well, but sometimes it returns id that does not belong to the newly created entry. I observed, that it even returns an id that is from another table that the insert was run for.
Let's say that I have tables A and B. Both have two columns, first is AUTO_INCREMENT and PRIMARY, and I run query like this through the layer:
INSERT IGNORE INTO `A` VALUES (NULL, "not really important value");
The query runs ok, but it returns id from the table B.
Why this happens? Any hint would be very appreciated.