【JavaEE】MyBatis配置(注解方式)

时间:2025-03-25 08:25:26
package person.hyy.test; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.RowBounds; 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 person.hyy.domain.User; import person.hyy.dao.UserDao; import person.hyy.domain.UserResult; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; public class MyBatisTest { private InputStream in; private SqlSessionFactoryBuilder builder; private SqlSessionFactory factory; private SqlSession session; private UserDao userDao; @Before public void init() throws IOException { in=Resources.getResourceAsStream(""); builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); session = factory.openSession(); userDao = session.getMapper(UserDao.class); } /*增加 && 主键回填*/ @Test public void testAddUser(){ User user = new User(); user.setName("小米"); user.setAge(23); user.setSex("W"); user.setAddr("广东"); System.out.println("增加"+userDao.addUser(user)+"条记录"); System.out.println(user); } /*修改*/ @Test public void testUpdateUser(){ User user = new User(); user.setId(5); user.setSex("M"); System.out.println("修改"+userDao.updateUser(user)+"条记录"); } /*删*/ @Test public void testDelUser(){ System.out.println("删除"+userDao.delUser(5)+"条记录"); } /*查*/ @Test public void testFindAll(){ List<User> users = userDao.findAll(); for(User user:users){ System.out.println(user); } } /*单项查询*/ @Test public void testFindById(){ User user = userDao.findById(3); System.out.println(user); } /*自动映射*/ @Test public void testFindNameWithAs(){ List<UserResult> users = userDao.findNameWithAs(); for(UserResult user:users){ System.out.println(user.getNameResult()); } } /*模糊查询*/ @Test public void testFindByName(){ List<User> users = userDao.findByName("%王%"); for(User user:users){ System.out.println(user); } } /*模糊查询改进*/ @Test public void testFindByName1(){ List<User> users = userDao.findByName1("张"); for(User user:users){ System.out.println(user); } } /*聚合查询*/ @Test public void testFindWithGroup(){ List<Map> listmap = userDao.findWithGroup(); for (Map map:listmap){ System.out.println(map.get("addr")+":"+map.get("count(id)")); } } /*分页查询*/ @Test public void testFindByRowBounds(){ RowBounds rowBounds = new RowBounds(0,3); List<User> users = userDao.findByRowBounds(20,rowBounds); for(User user:users){ System.out.println(user); } } @After public void destory() throws IOException { session.commit(); session.close(); in.close(); } }