【myBatis】SqlSession对象获取的封装工具类

myBatis 中需要 SqlSession对象中的方法来调用接口中的方法或通过反射取得接口对象,将SqlSession对象的获取封装,便于以后的使用

 

 

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



public class SqlSessionFactoryUtil {
	//mybatis的主配置文件路径
	private static String path="config/mybatis-config.xml";
	private static Reader read;
	private static SqlSessionFactory  factory=null;
	
	static {
		try {
			 read= Resources.getResourceAsReader(path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
/*	
 * 通过SqlSessionFactoryBuilder对象的build方法获得单例SqlSessionFactory工厂对象
*/
	private static SqlSessionFactory getFactory(){
		if(factory==null){
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			factory= builder.build(read);
		}
		return factory;
	}
	
//	通过SqlSessionFactory工厂对象取得SqlSession对象
	public static SqlSession  getSession(){
		SqlSession s=getFactory().openSession(true);
		return s;
	}

}
SqlSessionFactoryBuilder对象的build方法获得单例SqlSessionFactory工厂对象
*/
	private static SqlSessionFactory getFactory(){
		if(factory==null){
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			factory= builder.build(read);
		}
		return factory;
	}
	
//	通过SqlSessionFactory工厂对象取得SqlSession对象
	public static SqlSession  getSession(){
		SqlSession s=getFactory().openSession(true);
		return s;
	}

}

 

 

 

 

 

你可能感兴趣的:(mybatis)