MyBatis框架的insert节点-向数据库中插入数据
需求:使用mybatis框架中的insert元素节点向数据库中插入数据
UserMapper.xml
UserMapper.java
编写测试方法:
1 @Test 2 public void testAddUser() throws ParseException { 3 SqlSession sqlSession = null; 4 User user=new User(); 5 user.setUserCode("admin"); 6 user.setAddress("中国河北省张家口市"); 7 user.setGender(1); 8 user.setUserName("小黑"); 9 user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2019-10-24"));//注意要转化成date类型的数据 10 user.setUserPassword("111111"); 11 int count=0;//返回受影响的行数 12 try { 13 sqlSession = MyBatisUtil.createSqlSession(); 14 //使用mapper映射的方式实现 15 //userList2 = sqlSession.selectList("cn.smbms.dao.user.UserMapper.getUserListByUserName",userNameString); 16 //调用mapper接口的方式实现 17 count= sqlSession.getMapper(UserMapper.class).addUser(user); 18 // int i=1/0;//模拟异常 后台日志打印出rolling back表示没有插入成功,事务进行了回滚 19 mlogger.info("返回受影响的行数:" + count); 20 sqlSession.commit();//后台日志打印出rolling back表示没有提交事务,事务进行了回滚,所以必须得提交事务才行 21 } catch (Exception e) { 22 // TODO: handle exception 23 } finally { 24 // 最后一定要注意:关闭会话 25 MyBatisUtil.closeSqlSession(sqlSession); 26 27 } 28 29 30 }
运行结果:
1 [DEBUG] 2019-11-04 23:10:17,824 org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 304840113. 2 [DEBUG] 2019-11-04 23:10:17,834 cn.smbms.dao.user.UserMapper.addUser - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@122b7db1] 3 [DEBUG] 2019-11-04 23:10:17,834 cn.smbms.dao.user.UserMapper.addUser - ==> Preparing: insert into smbms_user(userName,userPassword,userCode,gender,birthday,address) values(?,?,?,?,?,?) 4 [DEBUG] 2019-11-04 23:10:17,944 cn.smbms.dao.user.UserMapper.addUser - ==> Parameters: 小黑(String), 111111(String), admin(String), 1(Integer), 2019-10-24 00:00:00.0(Timestamp), 中国河北省张家口市(String) 5 [INFO] 2019-11-04 23:10:17,954 cn.smbms.dao.test.UserMapperTest - 返回受影响的行数:1 6 [DEBUG] 2019-11-04 23:10:17,954 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@122b7db1] 7 [DEBUG] 2019-11-04 23:10:17,954 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@122b7db1] 8 [DEBUG] 2019-11-04 23:10:17,954 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@122b7db1] 9 [DEBUG] 2019-11-04 23:10:17,954 org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 304840113 to pool.