MyBatis从入门到精通:第一章测试代码

package tk.mybatis.simple.mapper;

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 tk.mybatis.simple.model.Country;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class CountryMapperTest{

    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init(){
        try{
            /*
                通过Resources工具类将配置文件读入Reader,再通过SqlSessionFactoryBuilder
                建造类对象使用Reader对象创造SqlSessionFactory工厂对象。在SqlSession的创建
                过程中,首先解析mybatis-config.xml配置文件,读取配置文件中的mappers配置后
                会去读全部的Mapper.xml进行具体的方法的解析。这些解析完成后,SqlSessionFactory
                就包含了所有的属性配置和执行SQL的信息。
             */
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testSelectAll(){

        /*
            使用时,通过SqlSessionFactory工厂对象获取一个SqlSession。通过
            SqlSession的selectList方法查找到CountryMapper.xml中id="selectAll"
            的方法,执行SQL查询。
         */

        SqlSession sqlSession=getSqlSession();

        try{
            /*
                MyBatis底层使用JDBC执行SQL,获得查询过结果集ResultSet后,根据ResultType
                的配置,将结果集映射为Country类型的集合,返回查询结果。这样就得到了最后的查询
                结果countryList。
             */
            List<Country> countryList = sqlSession.selectList("tk.mybatis.simple.mapper.CountryMapper.selectAll");
            printCountryList(countryList);
        }finally {
            /*
                完成所有工作后,一定需要将SqlSession关闭,否则会因为连接没有
                关闭,导致数据库连接数过多,造成系统崩溃。
             */
            sqlSession.close();
        }
    }


    private void printCountryList(List<Country> countryList){
        for(Country country:countryList){

            try {
                System.out.printf("%-4d%4s%4s\n",
                        country.getId(),
                        //new String(country.getCountryname().getBytes("utf-8")),
                        new String(country.getCountryname().getBytes()),
                        country.getCountrycode());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                System.out.println("test");
            }
        }
    }

    public SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

猜你喜欢

转载自www.cnblogs.com/junjie2019/p/10567071.html