使用mybatis插入数据的时候日志记录如下:
[DEBUG][main][2017-05-08 10:52:24][org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@54c5a2ff]
[DEBUG][main][2017-05-08 10:52:24][org.apache.ibatis.logging.jdbc.BaseJdbcLogger] - ==> Preparing: update user SET username = ?, address = ? where id = ?
[DEBUG][main][2017-05-08 10:52:24][org.apache.ibatis.logging.jdbc.BaseJdbcLogger] - ==> Parameters: 谢尔盖布林(String), 硅谷(String), 40(Integer)
[DEBUG][main][2017-05-08 10:52:24][org.apache.ibatis.logging.jdbc.BaseJdbcLogger] - <== Updates: 1
显示是执行成功了的,但是返回数据库查询却不能查询到数据。测试发现数据库主键已经自动增加。
主要原因就是mybatis不会自动提交事物。
关键代码:
@Before
public void before() throws Exception {
String resource = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = sqlSessionFactory.openSession();
userDao = sqlSession.getMapper(UserDao.class);
}
@Test
public void testInsertSelective() throws Exception {
//TODO: Test goes here...
User user=new User();
user.setUsername(System.currentTimeMillis()+"");
int i = userDao.insertSelective(user);
//添加这一句代码
sqlSession.commit();
System.out.println(i); }}