首页 > 解决方案 > How to return multiple generated columns after insert in MyBatis(Oracle)

问题描述

I have table with primary key, which consist of several columns. There is batch insert with special Oracle hook - ignore_row_on_dupkey_index. That hook allow to ignore Unique Constraint Exception, duplicate records just get ignored, whereas non duplicate get successfully inserted. Using simple jdbc I could easily return primary key(consist of several columns) by code:

try(PreparedStatement st = connectio.preparedStatement("insert /* ignore_row_on_dupkey(Table_name, Constraint) */ into TABLE(c1, c2, c3) values(?,?,?)", new String [] {"c1", "c2"})) {
//Batch insert then get generated keys
}

Then I could analyze duplicates by iterating over returned keys.

I want to achieve this the same by MyBatis. I found Options annotation, which allows to do it by setting property useGeneratedKeys and keyColumn. The problem is I have complex primary key, whereas keyColumn has type String. Also I dont want to use SelectKey annotation.

So my question is can I return several columns value and how by MyBatis or not?

Thank you.

标签: javaoraclejdbcmybatis

解决方案


keyColumn允许指定多个列。这是文档的相关部分(注意最后一句):

键列 | (仅限插入和更新)使用生成的键设置表中列的名称。仅当键列不是表中的第一列时,某些数据库(如 PostgreSQL)才需要这样做。如果需要生成多个列,则可以是逗号分隔的列名列表。

还有一个来自 mybatis测试的例子:

<insert id="insertTable2WithGeneratedKeyXml" useGeneratedKeys="true"
    keyProperty="nameId,generatedName" keyColumn="ID,NAME_FRED">
  insert into table2 (name) values(#{name})
</insert>

推荐阅读