代码
package gua;
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;
/**
* zt
* 2020/9/27
* 19:59
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
//静态代码块,在方法调用之前调用,而且只调用一次
static {
System.out.println("在静态代码块中ongoing给sqlSessionFactory做初始化");
try {
//1.把配置文件转成一个流
InputStream is = Resources.getResourceAsStream("mybatisConfig.xml");
//2.初始化sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}