今天我们学习一下mybatis框架中的update节点元素的使用
需求:修改用户表中的一条数据记录,修改编号为21的用户的密码
UserMapper.xml
UserMapper.java
编写测试方法:
1 @Test 2 public void testUpdate() { 3 SqlSession sqlSession = null; 4 User user=new User(); 5 user.setUserPassword("000000"); 6 user.setId(21); 7 8 int count=0;//返回受影响的行数 9 try { 10 sqlSession = MyBatisUtil.createSqlSession(); 11 //调用mapper接口的方式实现 12 count= sqlSession.getMapper(UserMapper.class).updateUser(user); 13 // int i=1/0;//模拟异常 后台日志打印出rolling back表示没有插入成功,事务进行了回滚 14 mlogger.info("返回受影响的行数:" + count); 15 sqlSession.commit();//后台日志打印出rolling back表示没有提交事务,事务进行了回滚,所以必须得提交事务才行 16 } catch (Exception e) { 17 // TODO: handle exception 18 } finally { 19 // 最后一定要注意:关闭会话 20 MyBatisUtil.closeSqlSession(sqlSession); 21 22 } 23 24 25 }
运行结果:
[DEBUG] 2019-11-05 21:03:24,121 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection [DEBUG] 2019-11-05 21:03:24,695 org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1720854532. [DEBUG] 2019-11-05 21:03:24,701 cn.smbms.dao.user.UserMapper.updateUser - ooo Using Connection [[email protected]] [DEBUG] 2019-11-05 21:03:24,703 cn.smbms.dao.user.UserMapper.updateUser - ==> Preparing: update smbms_user set userPassword =? where id=? [DEBUG] 2019-11-05 21:03:25,084 cn.smbms.dao.user.UserMapper.updateUser - ==> Parameters: 000000(String), 21(Integer) [INFO] 2019-11-05 21:03:25,087 cn.smbms.dao.test.UserMapperTest - 返回受影响的行数:1 [DEBUG] 2019-11-05 21:03:25,088 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [[email protected]] [DEBUG] 2019-11-05 21:03:25,093 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [[email protected]] [DEBUG] 2019-11-05 21:03:25,095 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [[email protected]] [DEBUG] 2019-11-05 21:03:25,097 org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 1720854532 to pool.
数据库查询结果:
原文地址:https://www.cnblogs.com/dongyaotou/p/11801639.html
时间: 2024-10-06 01:10:42