SSM-MyBatis-10:Mybatis中SqlSession的getMapper()和简单的工具类MyBatisUtils
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
getMapper的作用,获取到接口,直接通过点的方式调用方法,以免直接手打的方式写错方法名,(强类型的方式)
例子:
IBookDAO mapper = session.getMapper(IBookDAO.class); List<Book> list = mapper.findAllBook();
那个工具类,主要是获取SqlSession对象,写法
package cn.dawn.util; 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 java.io.IOException; import java.io.InputStream; /** * Created by Dawn on 2018/2/24. */ public class MyBatisUtils { static String path = "mybatis-config.xml"; static InputStream e; static SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); static SqlSessionFactory factory; static { try { e = Resources.getResourceAsStream(path); factory = builder.build(e); } catch (IOException e1) { e1.printStackTrace(); } } public static SqlSession getSession(){ return factory.openSession(); } }
他这个方法怎么使用呢?
如下:
SqlSession session= MyBatisUtils.getSession();