
src/test/java/com/artchips/test/InfoTest.java
import java.io.IOException;import java.io.Reader;import java.util.List;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.BeforeClass;import org.junit.Test;import com.artchips.bean.Info;public class InfoTest {private static SqlSessionFactory sqlSessionFactory;@BeforeClass // 必须配合static一起用public static void init() {try(Reader reader = Resources.getResourceAsReader("mybatis-config.xml");){sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();}}@Testpublic void testSelectAll(){SqlSession sqlSession = sqlSessionFactory.openSession();try {List<Info> infoList = sqlSession.selectList("com.artchips.bean.Info.selectAllInfo");if (infoList != null && infoList.size() > 0) {infoList.forEach(info -> {System.out.println(info);});}} finally {sqlSession.close();}}}
执行过程:
(读配置)通过Resources工具类将mybatis-config.xml配置文件读入到Reader。
(创建SqlSessionFactory工厂对象)在通过SqlSessionFactoryBuilder建造类使用Reader创建SqlSessionFactory工厂对象
在创建SqlSessionFactory对象的过程中:
(获取SqlSession)使用时通过SqlSessionFactory工厂获取SqlSession。
(SQL查询)通过SqlSession的selectList方法查找到InfoMapper.xml中的id=”selectAll”的方法,执行SQL查询。
(返回结果)MyBatis底层使用的JDBC执行SQL,获得查询结果集ResultSet后,根据resultType的配置将结果映射到Info类的集合,返回查询结果。
(关闭sqlSession)使用完毕后一定要关闭sqlSession,避免造成过多连接没有关闭导致数据库锁或者更严重的系统异常等。