SSM-MyBatis-10:Mybatis中SqlSession的getMapper()和簡單的工具類MyBatisUtils
阿新 • • 發佈:2018-02-24
dao input eat -m style nfa put creat factor
------------吾亦無他,唯手熟爾,謙卑若愚,好學若饑-------------
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();
SSM-MyBatis-10:Mybatis中SqlSession的getMapper()和簡單的工具類MyBatisUtils