我需要在插入记录后使用spring jdbc模板检索自定义自动生成的密钥。
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)
如果你看到我使用序号。下一个带有" CRE"前缀的序列。作为主键值。目的是拥有像CRE1,CRE2,CRE3 ...... CREn这样的键。我希望使用spring jdbc模板检索它。这是我写的代码,但它抛出异常。
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;
}
记录完美地插入到数据库中。抛出以下异常
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)
有没有办法检索主键值?
答案 0 :(得分:1)
这是解决方案,而不是使用
String creditId = keyHolder.getKey().toString();
我们应该使用
String creditId = (String) keyHolder.getKeys().get("CREDITID");
实际提示来自Unknown先生。我不能接受你的回答,因为它不正确,但感谢暗示了一个不同的方向。