package com.heima.test; import com.heima.dao.UserDao; import com.heima.pojo.QueryVo; import com.heima.pojo.User; 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.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class TestHeiMa { private InputStream in; private SqlSession sqlSession; private UserDao userDao; //初始化 @Before public void init() throws Exception{ //1、读取配置文件 in = Resources.getResourceAsStream("mybatis-config.xml"); //2、读取sqlsessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3、读取session对象 sqlSession = factory.openSession(); //4、获取dao的代理对象 userDao = sqlSession.getMapper(UserDao.class); } //释放资源和提交事务 @After public void destroy() throws Exception{ //6、释放资源 sqlSession.commit(); sqlSession.close(); in.close(); } //查询所有 @Test public void test(){ //5、执行查询所有方法 List<User> list = userDao.findAll(); for(User user : list){ System.out.println(user); } } //添加 @Test public void add(){ User user = new User(); user.setUsername("cccc"); user.setPassword("1521"); user.setRealName("阿德"); user.setSex("男"); user.setAge(12); System.out.println("保存前"+user); userDao.insert(user); System.out.println("保存后"+user); } //修改 @Test public void update(){ User user = new User(); user.setUserId(6); user.setUsername("myadd"); user.setPassword("1521"); user.setRealName("阿德"); user.setSex("女"); user.setAge(19); userDao.update(user); } //删除 @Test public void delete(){ userDao.delete(6); } //查询一个 @Test public void findOne(){ User user = userDao.findOne(1); System.out.println(user); } //模糊查询 @Test public void findByName(){ List<User> users = userDao.findByName("%s%"); for(User user : users){ System.out.println(user); } } //查询记录条数 @Test public void findTotal(){ Integer total = userDao.findTotal(); System.out.println(total); } //使用实体类包装对象作为查询条件 @Test public void queryVo(){ QueryVo vo=new QueryVo(); User user=new User(); user.setUsername("%w%"); vo.setUser(user); List<User> users = userDao.queryVo(vo); for(User u : users){ System.out.println(u); } } //条件查询 @Test public void findUserByCondition(){ User user=new User(); user.setUsername("wangwu"); user.setSex("女"); List<User> userByCondition = userDao.findUserByCondition(user); for (User user1 : userByCondition) { System.out.println(user1); } } /*** * 使用foreach标签查询多个id的信息 */ @Test public void findUserIds(){ QueryVo queryVo = new QueryVo(); ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(3); list.add(2); queryVo.setIds(list); List<User> userIds = userDao.findUserIds(queryVo); for (User userId : userIds) { System.out.println(userId); } } }
在bilibili看了老师的视频,讲解十分到位,自己的测试,若有错误,欢迎指正