简体   繁体   English

使用SimpleJdbcInsert和Sybase检索生成的密钥时出现问题

[英]Issue retrieving generated keys with SimpleJdbcInsert and Sybase

I'm having an odd problem with SimpleJdbcInsert.executeAndReturnKey with Sybase (jTDS driver) and certain data. 我在使用带有Sybase(jTDS驱动程序)和某些数据的SimpleJdbcInsert.executeAndReturnKey时遇到了一个奇怪的问题。

Take the following example: 请看以下示例:

SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate)
    .withTableName("TABLE_NAME")
    .usingGeneratedKeyColumns("ID");

List<String> columns = new ArrayList<String>();
    columns.add("SOME_NUMERIC_DATA");
    columns.add("SOME_STRING_DATA");

Map<String, Object> params = new HashMap<String, Object>();
params.put("SOME_NUMERIC_DATA", 10.02);
params.put("SOME_STRING_DATA", "AAAA");

Number insertId = insert.executeAndReturnKey(params);

The above will fail with 以上将失败

DataIntegrityViolationException: Unable to retrieve the generated key for the insert

The insert itself is fine as if I do an insert.execute(params) the insert will work correctly (but I need the generated column value). 插入本身很好,就像我执行insert.execute(params) ,插入将正常工作(但我需要生成的列值)。

If I insert null instead of 10.02 for the SOME_NUMERIC_DATA column then it will work correctly and return the generated column value. 如果我为SOME_NUMERIC_DATA列插入null而不是10.02 ,则它将正常工作并返回生成的列值。 Also if all of the fields are VARCHAR / String then it will work correctly. 同样,如果所有字段都是VARCHAR / String则它将正常工作。

Can anyone see anything here that might be causing this with a combination of string and numeric fields. 任何人都可以在这里看到任何由字符串和数字字段组合导致的问题。

I should also add that when I use the exact same code with an H2 database it works all of the time - this seems to be related to Sybase/jTDS 我还应该补充一点,就是当我在H2数据库中使用完全相同的代码时,它始终有效-这似乎与Sybase / jTDS有关

I had the same problem with SQL Server and fixed it by calling this configuration method right before the call to executeAndReturnKey() : 我在使用SQL Server时遇到了同样的问题,并通过在调用executeAndReturnKey()之前立即调用此配置方法来解决此问题:

mySimpleJdbcInsert.setAccessTableColumnMetaData(false);

I suspect the error has to do with database metadata : as explained in the spring reference http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/jdbc.html , SimpleJdbcInsert uses database metadata to construct the actual insert statement. 我怀疑错误与数据库元数据有关:如spring参考http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/jdbc.html中所述 ,SimpleJdbcInsert使用数据库元数据来构造实际的插入语句。

One could also use the SQL OUTPUT clause such as 也可以使用SQL OUTPUT子句,例如

INSERT INTO myTable (Name, Age)
OUTPUT Inserted.Id
VALUES (?,?)

And use some more generic JdbcTemplate.execute() to handle the insert. 并使用一些更通用的JdbcTemplate.execute()来处理插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM