Reputation: 289
I am required to retrieve customized auto-generated key using spring jdbc template after insertion of a record.
insert into CREDIT(CREDITID,PROFILEID,CLIENTID,EVENTID,CREDIT_HEADING,CREDIT_DESCRIPTION,CREDIT_IMAGE,TESTIMONIAL,TESTIMONIAL_PROVIDER) values('CRE'||CREDITID_SEQ.nextVal,:profileId,:clientId,:eventId,:creditHeading,:creditDescription,:creditImage,:testimonial,:provider)
If you see i am using a sequence.nextVal prefixed with "CRE" as primary key value. The purpose is to have keys like CRE1, CRE2,CRE3....CREn . I wish to retrieve it using spring jdbc template. Here is the code i have written but it throws an exception.
public String insertCredit(final Credit credit) throws SQLException {
final String insertQuery = dbUtil.getQuery("crms.credit.insert");
SqlParameterSource creditParameters = new BeanPropertySqlParameterSource(credit);
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
NamedParameterJdbcTemplate namedParamJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
namedParamJdbcTemplate.update(insertQuery, creditParameters, keyHolder, new String[]{"CREDITID"});
String creditId = keyHolder.getKey().toString();
return creditId;
}
The record is perfectly inserted into the database. following exception is thrown
org.springframework.dao.DataRetrievalFailureException: The generated key is not of a supported numeric type. Unable to cast [java.lang.String] to [java.lang.Number]
at org.springframework.jdbc.support.GeneratedKeyHolder.getKey(GeneratedKeyHolder.java:73)
at com.bluebench.mediamanager.cmn.dao.crms.CreditDAO.insertCredit(CreditDAO.java:72)
at com.bluebench.mediamanager.crms.service.CredentialManagementService.addCredit(CredentialManagementService.java:56)
at com.bluebench.mediamanager.crms.controller.CredentialManagementController.addCredits(CredentialManagementController.java:59)
Is there a way to retrieve the primary key value ?
Upvotes: 0
Views: 3253
Reputation: 289
Here is the solution, instead of using
String creditId = keyHolder.getKey().toString();
We should use
String creditId = (String) keyHolder.getKeys().get("CREDITID");
the actual hint came from Mr. Unknown. I cannot accept your answer since its not correct but thanks for hinting a different direction.
Upvotes: 2