不使用MyBatis配置文件获取SQL会话对象
public class TestUserMapperNew {
private SqlSession sqlSession; // SQL会话
private UserMapper userMapper; // 用户映射器
@Before
public void init() {
// 创建数据源
DataSource dataSource = new PooledDataSource("",
"jdbc:mysql://localhost:3306/testdb?useSSL=false", "root", "p@ssw0rd");
// 创建事务工厂
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// 创建数据库环境
Environment environment = new Environment("development", transactionFactory, dataSource);
// 基于环境创建配置对象
Configuration configuration = new Configuration(environment);
// 添加用户映射器接口
configuration.addMapper(UserMapper.class);
// 基于配置对象构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);
// 利用SQL会话工厂获取SQL会话
sqlSession = factory.openSession();
// 利用SQL会话获取用户映射器对象
userMapper = sqlSession.getMapper(UserMapper.class);
// 提示用户SQL会话对象创建成功
System.out.println("sqlSession对象已创建。");
}
@Test
public void testFindById() {
int id = 1;
User user = userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到。");
}
}
@Test
public void testFindAll() {
List<User> users = userMapper.findAll();
users.forEach(user -> System.out.println(user));
System.out.println();
for (int i = 0; i < users.size(); i++) {
System.out.println(users.get(i));
}
System.out.println();
for (User user : users) {
System.out.println(user);
}
}
@After
public void destroy() {
// 关闭SQL会话
sqlSession.close();
// 提示用户SQL会话对象关闭
System.out.println("sqlSession对象已关闭。");
}
}