MyBatis+Oracle 使用注解式实现 insert 并返回主键id

代码:
@Insert("INSERT INTO DAT_FLOOR " +
        " (STATUS, CREATER, CREATETIME, MODIFIER, MODIFYTIME, BELONGPAGE) " +
        " VALUES (#{status}, #{creater}, #{createTime}, #{modifier}, #{modifyTime}, #{belongPage})")
@Options(useGeneratedKeys=true, keyProperty="id")
int insert1(Floor floor);

报错:

org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column #1 from result set.  Cause: java.sql.SQLException: 无效的列类型: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor

把useGeneratedKeys改为false,解决报错,但不返回主键

原因:oracle数据库不支持自增,是使用序列实现的自增

解决方法:使用@SelectKey注解,

注意:

1.使用currVal 运算符来访问序列的值,否则每次主键的递增为2

2.before 应为 false

@SelectKey(statement = "SELECT FLOOR_SEQUENCE.currVal AS Id FROM DUAL ", before = false, keyColumn = "id", resultType = int.class, keyProperty = "id")
@Insert("INSERT INTO DAT_FLOOR " +
        " (STATUS, CREATER, CREATETIME, MODIFIER, MODIFYTIME, BELONGPAGE) " +
        " VALUES (#{status}, #{creater}, #{createTime}, #{modifier}, #{modifyTime}, #{belongPage})")
int saveOnlyId(Floor floor);

你可能感兴趣的:(MyBatis+Oracle 使用注解式实现 insert 并返回主键id)