在接口名称上按ctrl + shift+ t 快捷创建测试类.
package com.way.dao;import javabean.Student;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import org.apache.ibatis.io.Resources;import java.io.IOException;import java.io.InputStream;import java.util.List;public class StudentDaoTest {@Testpublic void queryStudentList() throws IOException {//1.mybatis的配置主文件名称String config = "mybatisConfig.xml";//2、读取mybatis.xml得到字节输入流,// Resources从类路径中加载资源。//getResourceAsStream读取的文件得到输入流InputStream inputStream = Resources.getResourceAsStream(config);//3、创建一个数据库会话工厂并调用它的建造方法,建造方法调用到读取资源的对象,并且赋值给了数据库工厂SqlSessionFactory builder = new SqlSessionFactoryBuilder().build(inputStream);//4、用sqlsession工厂对象打开session会话,获得session对象,得到sql语句执行类。SqlSession sqlSession = builder.openSession();//5、执行sql语句List<Object> list = sqlSession.selectList("com.way.dao.StudentDao.queryStudentList");//6、打印输出list.forEach(student1-> System.out.println(student1));//7、释放资源sqlSession.close();}@Testpublic void insertStudent() throws IOException {InputStream inputStream = null;SqlSessionFactory sessionFactory = null;SqlSession sqlSession = null;try {//1、读取mybatisConfig.xml配置文件(日志、数据库的连接、StudentDao的mapper配置文件)inputStream = Resources.getResourceAsStream("mybatisConfig.xml");//2、创建一个数据库会话工厂并调用它的建造方法,建造方法调用到读取资源的对象,并且赋值给了数据库工厂sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//3、得到sql语句执行类sqlSession = sessionFactory.openSession();//4、创建JavaBean类,//Student student = new Student();//5、执行slq语句int insert = sqlSession.insert("com.way.dao.StudentDao.insertStudent",new Student(4,"李武","5544@1360.com",30));sqlSession.commit();System.out.println(insert);//1} catch (IOException e) {e.printStackTrace();sqlSession.rollback();}finally {if (sqlSession != null) {sqlSession.close();}}}@Testpublic void updateSudent() throws IOException {InputStream inputStream = null;SqlSessionFactory sessionFactory = null;SqlSession sqlSession = null;try {//1、读取mybatisConfig.xml主配置文件inputStream = Resources.getResourceAsStream("mybatisConfig.xml");//2、sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);sqlSession = sessionFactory.openSession();int update = sqlSession.update("com.way.dao.StudentDao.updateSudent",new Student(3, "王五", "1565@qq.com", 22));sqlSession.commit();} catch (IOException e) {e.printStackTrace();sqlSession.rollback();} finally {if (sqlSession != null) {sqlSession.close();}}}@Testpublic void deleteStudnet() {SqlSession sqlSession = null;try {InputStream inputStream = Resources.getResourceAsStream("mybatisConfig.xml");SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);sqlSession = build.openSession();int delete = sqlSession.delete("com.way.dao.StudentDao.deleteStudnet", 4);sqlSession.commit();System.out.println(delete);} catch (IOException e) {e.printStackTrace();sqlSession.rollback();} finally {if (sqlSession != null) {sqlSession.close();}}}}
