💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
SqlSessionFactoryBuilder(静态代码块) SqlSessionFactory(单例) SqlSession(非线程安全-放到局部方法作用域) **实例** ~~~ package com.nobb.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; public class SqlSessionUtils { //不能赋值为Null 因为给了final 是不能重新赋值的 private static final SqlSessionFactory sqlSessionFactory; static{ //静态代码块:只会在类加载时执行,一个类在虚拟机开启期间只会被加载一次 String resource = "mybatis-config.xml"; InputStream inputStream = null; try{ inputStream = Resources.getResourceAsStream(resource); }catch(IOException e){ e.printStackTrace(); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } public static SqlSession openSession(){ //通过sqlSessionFactory获得session SqlSession session = sqlSessionFactory.openSession(); return session; } } ~~~ 测试基类 ~~~ package com.test; import com.nobb.util.SqlSessionUtils; import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Before; //测试基类 public class BaseTest { protected SqlSession session; @Before //每个测试方法执行前,会先执行 public void init(){ session = SqlSessionUtils.openSession(); } @After //每个测试方法执行后会执行 public void destroy(){ //提交事务 session.commit(); //关闭资源 session.close(); } } ~~~ **测试代码** ~~~ package com.test; import com.nobb.domain.User; import com.nobb.mapper.UserMapper; import org.junit.Test; import java.util.List; public class UserMapperTest extends BaseTest { @Test public void testFindAll(){ UserMapper mapper = session.getMapper(UserMapper.class); List<User> users = mapper.findAll(); System.out.println(users); } } ~~~