Mybatis update时返回主键
如何在update后返回主键
工作中遇到更新后想获取主键的操作,不想请求两次数据库,想着update后是否可以返回主键,(insert
时是可以直接使用useGeneratedKeys="true" keyProperty="id"
返回主键的,但需要通过pojo对象获取主键),于是网上搜索一番终于获得解决办法,在此记录一下。
<update id="updateSelective" parameterType="com.priv.test.pojo.Test">
<selectKey keyProperty='id' resultType='java.lang.String' order='AFTER'>
SELECT
id
from t_test
where uno= #{uno}
</selectKey>
update t_test
set t_id = #{tId,jdbcType=VARCHAR},
state = 2,
update_time = now()
where uno= #{uno}
</update>
2、Java中获取id,如下所示
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
TestMapper mapper = ac.getBean(TestMapper.class);
Test test= new Test();
test.setTId("f59906");
test.setUno("868297");
mapper.updateSelective(test);
System.out.println(test.getId());
}
输出结果
3f2559
SelectKey详解
<selectKey keyProperty='id' resultType='java.lang.String' order='BEFORE'>
此处的 keyProperty=’id’ 是指将查询出来的id 映射到传入updateSelective 的test 的id 。类型为String
order=’BEFORE’ 要在执行update之前进行查询,并把id返回出来, order=‘AFTER’ 在执行玩update之后进行查询,根据个人需求而定。
原文链接:https://blog.csdn.net/u012373815/java/article/details/73864866