【发布时间】:2018-04-16 07:37:03
【问题描述】:
我知道这是一个重复的问题,但其他页面上的其他解决方案对我不起作用。
我有一个 Oracle 数据库,我想获取插入的记录 ID(主键),但我无法这样做。以下是错误和我的代码。
org.springframework.dao.DataRetrievalFailureException: 生成的 键不是受支持的数字类型。无法投射 [oracle.sql.ROWID] 到 [java.lang.Number]
String query = "INSERT INTO JOBS (USERNAME, CREATED_ON, STATUS, JOBTYPE, DATA) " + "VALUES (?, ?, ?, ?, ?)";
try {
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "username");
ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
ps.setString(3, "status");
ps.setString(4, "jobtype");
ps.setString(5, "job-data");
return ps;
}
}, holder);
System.out.println("Holder tostring: " + holder.toString());
System.out.println("Ran an update statement and got generated key. Key = " + holder.getKey().intValue());
System.out.println("Key: " + holder.getKey().longValue());
return true;
} catch (DataAccessException e) {
System.err.println("Exception thrown inserting record into table. Error: " + e.getMessage());
e.printStackTrace();
}
当我在调试模式下运行应用程序时,我看到持有者变量 keyList 的值为:[{ROWID=AAAKy2AAAAALRgdAAD}] 我没有得到插入的记录 ID。
创建表脚本是:
CREATE TABLE JOBS (
ID INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 1 INCREMENT BY 1),
USERNAME VARCHAR2(20) NOT NULL,
CREATEDON TIMESTAMP NOT NULL,
STATUS VARCHAR2(10) NOT NULL,
JOBTYPE VARCHAR2(15) NOT NULL,
DATA VARCHAR2(1000 CHAR) NOT NULL,
PRIMARY KEY(ID)
);
【问题讨论】:
-
将 ID 从 INTEGER 更改为 NUMBER,您应该使用序列作为 ID。我不认为 oracle 使用 INTEGER 作为 data_type,除非您在数据库中将它们自己定义为自定义 data_type
-
嗨@logger,我将我的Jobs 表ID 更改为Number 并删除了Generated Always ... 并创建了用于生成ID 的序列并在插入命令上触发以在插入命令上添加ID 值。我仍然面临同样的问题。