public class TestStudentMapper {
SqlSessionFactory factory;
@Before
public void init(){
try {
InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
factory = sfb.build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test01(){
//开启事务自动提交
SqlSession sqlSession = factory.openSession(true);
//获取dao层的代理对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> students = studentDao.getAll();
students.forEach(student -> System.out.println(student));
}
@Test
public void test02(){ //添加数据
SqlSession sqlSession = factory.openSession(true);
Student student = Student.builder().stuSex("男").stuNo("2021073100").stuName("李四").stuBirth(new Date()).build();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Integer line = studentDao.addOne(student);
System.out.println(line);
}
@Test
public void test03(){//删除一条数据
SqlSession sqlSession = factory.openSession(true);
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Integer line = studentDao.delOne("李四");
System.out.println(line);
}
@Test
public void test04() { //修改数据
SqlSession sqlSession = factory.openSession(true);
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = Student.builder().stuSex("女").stuNo("2021073100").stuName("李四").stuBirth(new Date()).build();
Integer line = studentDao.updateOne(student);
System.out.println(line);
}
@Test
public void test06(){//模糊查询一个学生信息 一个参数
SqlSession sqlSession = factory.openSession(true);
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> students = studentDao.selectLikeName("li");
System.out.println(students.toString());
}
@Test
public void test07(){//模糊查询一个学生信息 两个参数
SqlSession sqlSession = factory.openSession(true);
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> students = studentDao.selectLikeName2("li", "2021072902");
System.out.println(students.toString());
}
@Test
public void test08(){//模糊查询一个学生信息 一个集合参数 mapper文件中按照key取值
SqlSession sqlSession = factory.openSession(true);
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
HashMap<String, String> map = new HashMap<>();
map.put("stuname","li");
map.put("stuno", "2021072902");
List<Student> students = studentDao.selectLikeName3(map);
System.out.println(students.toString());
}
}