今天我们学习一下mybatis框架中的update节点元素的使用
需求:修改用户表中的一条数据记录,修改编号为21的用户的密码
UserMapper.xml
UserMapper.java
编写测试方法:
@Test
public void testUpdate() {
SqlSession sqlSession = null;
User user=new User();
user.setUserPassword("000000");
user.setId(21); int count=0;//返回受影响的行数
try {
sqlSession = MyBatisUtil.createSqlSession();
//调用mapper接口的方式实现
count= sqlSession.getMapper(UserMapper.class).updateUser(user);
// int i=1/0;//模拟异常 后台日志打印出rolling back表示没有插入成功,事务进行了回滚
mlogger.info("返回受影响的行数:" + count);
sqlSession.commit();//后台日志打印出rolling back表示没有提交事务,事务进行了回滚,所以必须得提交事务才行
} catch (Exception e) {
// TODO: handle exception
} finally {
// 最后一定要注意:关闭会话
MyBatisUtil.closeSqlSession(sqlSession); } }
运行结果:
[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 [com.mysql.jdbc.JDBC4Connection@66922804]
[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 [com.mysql.jdbc.JDBC4Connection@66922804]
[DEBUG] 2019-11-05 21:03:25,093 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@66922804]
[DEBUG] 2019-11-05 21:03:25,095 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@66922804]
[DEBUG] 2019-11-05 21:03:25,097 org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 1720854532 to pool.
数据库查询结果: