当id / uuid存储为二进制时,如何在使用MyBatis插入后返回键?

时间:2011-08-26 13:28:57

标签: java mysql jdbc mybatis

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

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

来做
useGeneratedKeys="true" keyProperty="id"

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

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

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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方法来检索数据库内部生成的密钥(例如,像MySQL或SQL Server这样的RDBMS中的自动增量字段)。

答案 2 :(得分: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