mybatis 中的mapper接口问题

一直以来,使用ssm框架的时候,都是直接使用mybatis的mapper,使用@Autowired注解,今天看了一些东西后,才知道,原生态的mapper对象是这样生成的,如下所示


SqlSessionfactoryBuilder builder = new SqlSessionfactoryBuilder();


Reader reader = Resources.getResourceAsReader("mybatis-config.xxml");

SqlSessionFactory factory = builder.build(reader);


SqlSession session = factory.openSession();


AccountDao dao = session.getMapper(Account.class);


到此,Mapper对象已经生成完毕



下面是mybatisUtil的工具类

package util;

import java.io.IOException;
import java.io.InputStream;

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 MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    private static final ThreadLocal tl = new ThreadLocal();
    
	static{
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static SqlSession openSession(){
		return sqlSessionFactory.openSession();
	}
	
	//实战中用
	public static SqlSession getCurrentSession(){
		SqlSession sqlSession = tl.get();
		if(sqlSession==null){
			sqlSession = openSession();
			tl.set(sqlSession);
			return sqlSession;
		}else{
	    	return sqlSession;
		}
	}
	
	public static void closeSession(){
		SqlSession currentSession = getCurrentSession();
	    currentSession.close();
	    tl.remove();
		
	}
	
	public static Object getMapper(Class clazz){
		return getCurrentSession().getMapper(clazz);
	}
	
	
	public static void commit(){
		SqlSession currentSession = getCurrentSession();
		currentSession.commit();
		closeSession();
		
	}
	
	public static void rollback(){
		SqlSession currentSession = getCurrentSession();
		currentSession.rollback();
		closeSession();
	}
	
	
	
}


你可能感兴趣的:(mybatis,mapper对象)