package com.atguigu.mybatis.test;
import com.atguigu.mybatis.mapper.UserMapper;
import com.atguigu.mybatis.pojo.User;
import com.atguigu.mybatis.utils.SqlSessionUtil;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author beyondx
* @description
* @date Created in 2022/08/03/ 7:51
*/
public class MyBatisTest {
@Test
public void testInsert() throws IOException {
// 获取核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
// 获取 SqlSessionFactoryBuilder 对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 获取 SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
// 获取 sql的 会话对象 SqlSession, 是 MyBatis 提供的 操作数据库的对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 获取 UserMapper 的 代理 实现类对象; 返回 类型T 的 实例化对象
// 通过 代理模式, 帮我们 生成 对应的 实现类, 帮我们 重写了方法
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 调用 mapper 接口中的 方法, 实现 添加 用户信息 的功能
mapper.insertUser();
// System.out.println("结果: " + result);
// sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdate() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser();
sqlSession.close();
}
@Test
public void testDelete() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser();
sqlSession.close();
}
@Test
public void testGetUserById() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById();
System.out.println(userById);
sqlSession.close();
}
@Test
public void testGetAllUser() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> allUser = mapper.getAllUser();
// for(User user : allUser) {
// System.out.println(user);
// }
// list中的 forEach方法
allUser.forEach(System.out::println);
sqlSession.close();
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/278683.html