I won’t mention all the benefits of using Spring JdbcTemplate over a classic use of Jdbc. However, there is still one thing which
bothers me from time to time. And, this is the absence of an easy way to get the generated fields after inserting a new row in the DB.
The use case is quite common especially nowadays with Rest APIs. Indeed, when you create an object you are suppose to return the link to
the newly created resource. The problem is the ID of the resource is most likely generated via a sequence and by using the common
jdbcTemplate methods you don’t have access to it.
Fortunately, there is still a way to get it!
Pretending there is table NOTIFICATION and a SEQUENCE to increment the primary key.
Here the Notification POJO:
So, how could we get the ID generated by the sequence? well, there is one method which can be used:
This method uses a keyHolder which will receive the value of the generated columns.
Let’s see how it works!
As we can see this solution is not perfect because we still need to create the prepare statement and set the parameters in the right order
with the right method according to the type. Well! it’s not too bad and it works with any kind of generated values, so it’s a good