Java 当id/uuid as存储为二进制时,如何在使用MyBatis插入后返回密钥?
我们目前在数据库中有触发器,可以为我插入的每个记录分发uuid。当我使用mybatis插入记录时,我希望返回uuid,而不是插入的行数 从上一篇文章中我读到我可以用Java 当id/uuid as存储为二进制时,如何在使用MyBatis插入后返回密钥?,java,mysql,jdbc,mybatis,Java,Mysql,Jdbc,Mybatis,我们目前在数据库中有触发器,可以为我插入的每个记录分发uuid。当我使用mybatis插入记录时,我希望返回uuid,而不是插入的行数 从上一篇文章中我读到我可以用 useGeneratedKeys="true" keyProperty="id" 但是我们将uuid存储为二进制文件,所以我想从insert中获取非二进制uuid。当我们插入东西时,我们使用像“uuid2bin”和“bin2uuid”这样的函数,所以我希望使用这样的函数从数据库(MySQL)检索新生成的uuid 关于如何取回新生成
useGeneratedKeys="true" keyProperty="id"
但是我们将uuid存储为二进制文件,所以我想从insert中获取非二进制uuid。当我们插入东西时,我们使用像“uuid2bin”和“bin2uuid”这样的函数,所以我希望使用这样的函数从数据库(MySQL)检索新生成的uuid
关于如何取回新生成的uuid有什么建议吗?我可以想到两个选项:1)使用MyBatis
TypeHandler在Java中进行转换,或2)使用返回格式化uuid的存储过程包装插入
#1的问题是您正在将负载从数据库移动到应用程序,如果MySql是远程的,这可能会影响性能
对于#2,您需要在MyBatis中使用
。但是,您需要确保它实际提交。另外,如果您正在使用MyBatis缓存,还需要在
中设置flushCache=true
,我将在
标记中使用
标记
<insert>
<selectKey keyProperty="pk" resultType="Type" order="AFTER">
select myDBFunction( (select triggerGeneratedColumnInBinary from myTable where pk = triggerLogicToRetrieveLastGenerated(...) ) );
</selectKey>
...procedure call or insert...
</insert>
useGeneratedKeys对您没有帮助,因为它告诉MyBatis使用JDBC getGeneratedKeys方法检索数据库内部生成的键(例如,像MySQL或SQL Server这样的RDBMS中的自动增量字段).p>方法返回一个值,该值是更新的行数。传入参数的id是insertd行的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
计入成本
身份证件
名称
#{id,jdbcType=BIGINT},
#{name,jdbcType=TIMESTAMP},
CostDO CostDO=新CostDO();
成本设置名称(“测试”);
int updateNum=productMapper.insertSelectiveReturnKey(costDO);
//UpdateEnum是更新的行数。
productMapper.InsertReturnKey(costDO);
int id=costDO.getId();
//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