[英]How to return key after insert using MyBatis when the id/uuid as is stored as binary?
我们目前在我们的数据库中有触发器,为我插入的每条记录分发uuid。 当我使用mybatis插入记录时,我希望将uuid取回而不是已插入的行数。
从上一篇文章我读到我可以做到
useGeneratedKeys="true" keyProperty="id"
但是我们将我们的uuid存储为二进制文件,所以我想从插入中获取非二进制uuid。 当我们插入东西时,我们使用'uuid2bin'和'bin2uuid'之类的函数,所以我希望使用这样的函数从数据库(MySQL)中检索新生成的uuid。
关于如何让新生成的uuid回来的任何建议?
我能想到的1两个选项)使用MyBatis的Java中的转换做TypeHandler
或2)与返回格式化的UUID存储过程包装你的插件。
#1的问题在于您正在将负载从数据库移动到您的应用程序,如果MySql是远程的,可能会对性能产生影响。
使用#2,您需要在MyBatis中使用<select>
。 但是,您需要确保它实际提交。 此外,如果您正在使用MyBatis缓存,还需要在<select>
设置flushCache=true
。
我会在<insert>
标记内使用<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中的自动增量字段)。
方法返回一个值是更新行的数量。传入参数的id是insertd row.as的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.