问题
先测试查找的时候没有任何问题,通过了,也出结果了
然后进行下面的插入测试时候,也没有问题,也通过了
public class TestMyBatis {
@Test
public void testSelectStudents(){
/**
* 使用mybatis的动态代理机制,使用SqlSession.getMapper(dao接口)
* getMapper能获取 dao接口对应的实现类对象
*/
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
//调用dao的方法,执行数据库的操作
List<Student> students = dao.selectStudents();
for (Student student : students){
System.out.println("学生=" + student);
}
}
@Test
public void testInsertStudent(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(1005);
student.setName("胖鱼");
student.setAge(18);
student.setEmail("yubb@163.com");
int nums = dao.insertStudent(student);
sqlSession.commit();
System.out.println("添加对象:"+nums);
}
}
但是再次进行查询的时候就报错了
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project 03-proxy-dao: There are test failures.
Please refer to E:\Java\mybatis\mybatis-course\03-proxy-dao\target\surefire-reports for the individual test results.
原因:
在测试报告中找到了问题:
### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '1005' for key 'PRIMARY'
"1005"是主键并且唯一,不能重复
然后猜测是不是在执行第一个测试的时候他会把所有的测试都执行一遍
解决方法
我注释掉了下面的插入,再次执行查找 ,成功。
这次我放开了下面的插入代码,把插入的代码更新了一下
@Test
public void testInsertStudent(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(1006);
student.setName("星熊童子");
student.setAge(38);
student.setEmail("xxtz@163.com");
int nums = dao.insertStudent(student);
sqlSession.commit();
System.out.println("添加对象:"+nums);
}
先不运行插入代码,直接查找
学生=Student{id=1001, name='李四', email='lisi@qq.com', age=20}
学生=Student{id=1002, name='张三', email='zs@qq.com', age=28}
学生=Student{id=1003, name='张飞', email='zhangfei@163.com', age=20}
学生=Student{id=1004, name='hanhan', email='hh@163.com', age=14}
学生=Student{id=1005, name='胖鱼', email='yubb@163.com', age=18}
学生=Student{id=1006, name='星熊童子', email='xxtz@163.com', age=38}
查找成功,并且下面的插入也先运行了
由此猜测 :在测试的时候会先把所有的代码运行完最后再进行测试。