Most of the time, the primary key is auto generated and once a row is inserted it is a common requirement to fetch auto generated primary key value after insert statement execution.So in this topic we will take a look into fetching that auto generated primary key once an insert statement is executed.We will implement this fetching of auto generated primary key while inserting through jdbctemplate and also namedparameterjdbctemplate using KeyHolder interface provided by spring.
KeyHolder Interface is for retrieving keys, typically used for auto-generated keys as potentially returned by JDBC insert statements.
Implementations of this interface can hold any number of keys. In the general case, the keys are returned as a List containing one Map for each row of keys.
Most applications only use on key per row and process only one row at a time in an insert statement. In these cases, just call getKey to retrieve the key. The returned value is a Number here, which is the usual type for auto-generated keys.
Following is the implementation using NamedParameterJdbcTemplate to fetch auto generated primary key value after insert statement execution.
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
©2017, DevGlan. All Rights Reserved.
Contact us: firstname.lastname@example.org