使用 Spring Data JDBC v1.0.4(不是 JPA)在 Oracle DB 中插入时出现以下错误:
Caused by: org.springframework.dao.DataRetrievalFailureException: The generated key is not of a supported numeric type. Unable to cast [oracle.sql.ROWID] to [java.lang.Number]
at org.springframework.jdbc.support.GeneratedKeyHolder.getKey(GeneratedKeyHolder.java:79) ~[spring-jdbc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.data.jdbc.core.DefaultDataAccessStrategy.getIdFromHolder(DefaultDataAccessStrategy.java:323) ~[spring-data-jdbc-1.0.4.RELEASE.jar:1.0.4.RELEASE]
at org.springframework.data.jdbc.core.DefaultDataAccessStrategy.insert(DefaultDataAccessStrategy.java:111) ~[spring-data-jdbc-1.0.4.RELEASE.jar:1.0.4.RELEASE]
at org.springframework.data.jdbc.core.DefaultJdbcInterpreter.interpret(DefaultJdbcInterpreter.java:73) ~[spring-data-jdbc-1.0.4.RELEASE.jar:1.0.4.RELEASE]
at org.springframework.data.relational.core.conversion.DbAction$InsertRoot.doExecuteWith(DbAction.java:110) ~[spring-data-jdbc-1.0.4.RELEASE.jar:1.0.4.RELEASE]
at org.springframework.data.relational.core.conversion.DbAction.executeWith(DbAction.java:55) ~[spring-data-jdbc-1.0.4.RELEASE.jar:1.0.4.RELEASE]
似乎默认实现总是需要一个自动生成的键,但我的表的主键是一个字符串。
要持久化的实体:
@Table("USERS")
public class User implements Persistable<String> {
@Transient
@JsonIgnore
private boolean newRow = false;
@Id
@Column("ID_USER")
private String userId;
@Column("NAME")
private String name;
@Override
@JsonIgnore
public String getId() {
return userId;
}
public void setNew(boolean newRow) {
this.newRow = newRow;
}
@Override
@JsonIgnore
public boolean isNew() {
return newRow;
}
}
存储库:
@Repository
public interface UserRepository extends CrudRepository<User, String>, PagingAndSortingRepository<User, String> {
}
对存储库的调用:
public User create(User user) throws QOException {
user.setNew(true);
return userRepository.save(user);
}
异常在insert
方法的最后一行抛出org.springframework.data.jdbc.core.DefaultDataAccessStrategy
:
operations.update( //
sql(domainType).getInsert(parameters.keySet()), //
parameterSource, //
holder //
);
// Next line is the problem
return getIdFromHolder(holder, persistentEntity);
问题是 KeyHolder 接口有一个getKey
返回 Number 的方法,Oracle 作为生成的 KEY 返回 ROWID ...但是实体 PK 没有生成,ID 是在插入之前设置的。
我无法理解该代码有什么问题,欢迎提供任何帮助。