3

我们目前在我们的数据库中有触发器,可以为我插入的每条记录分发 uuid。当我使用 mybatis 插入记录时,我想取回该 uuid 而不是已插入的行数。

从上一篇文章中我读到我可以做到

useGeneratedKeys="true" keyProperty="id"

但是我们将我们的 uuid 存储为二进制文件,所以我想从插入中获取非二进制 uuid。当我们插入东西时,我们使用像'uuid2bin'和'bin2uuid'这样的函数,所以我希望使用这样的函数从数据库(MySQL)中检索新生成的uuid。

关于如何取回新生成的 uuid 的任何建议?

4

3 回答 3

1

我能想到的两个选项 1) 使用 MyBatis 在 Java 中进行转换TypeHandler或 2) 使用返回格式化 UUID 的存储过程包装您的插入。

#1 的问题是您正在将负载从数据库转移到您的应用程序,如果 MySql 是远程的,这可能会对性能产生影响。

使用#2,你需要<select>在 MyBatis 中使用 a。但是,您需要确保它实际提交。另外,如果你使用的是 MyBatis 缓存,你还需要flushCache=true<select>.

于 2011-08-26T17:35:47.653 回答
0

我会在<selectKey>标签内使用<insert>标签

<insert>
   <selectKey keyProperty="pk" resultType="Type" order="AFTER">
     select myDBFunction( (select triggerGeneratedColumnInBinary from myTable where pk = triggerLogicToRetrieveLastGenerated(...) ) );
   </selectKey>
   ...procedure call or insert...
</insert>

如果您发送的是对象而不是 Hashmap,则此代码将在插入后使用触发器生成的列设置解释器函数的结果。该方法仍将返回行数,但您的对象将拥有它的键。

System.out.println(myObject.getPk()); //0
int rows = myMapper.insertMyClass(myObject); // sets the pk
System.out.println(myObject.getPK()); //324

useGeneratedKeys 不会帮助你,因为它告诉 MyBatis 使用 JDBC getGeneratedKeys 方法来检索数据库内部生成的键(例如,在 RDBMS 中,如 MySQL 或 SQL Server 中的自动递增字段)。

于 2015-08-23T03:26:23.913 回答
0

方法返回值是更新的行数。传入参数的id是插入行的id。如下:

 <insert id="insertSelectiveReturnKey" parameterType="com.test.dal.model.CostDO" useGeneratedKeys="true" keyProperty="id">
        insert into cost
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                name,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=BIGINT},
            </if>
            <if test="name != null">
                #{name,jdbcType=TIMESTAMP},
            </if>
        </trim>
    </insert>


 CostDO costDO = new CostDO();
 costDO.setName("test");
 int updateNum = productMapper.insertSelectiveReturnKey(costDO);
 // updateNum is the number of updated rows.

productMapper.insertSelectiveReturnKey(costDO);
int id = costDO.getId();
// id is the id of insertd row
于 2019-07-01T03:01:16.767 回答