大数据------JavaWeb------MyBatis(完整知识点汇总)

时间:2024-07-04 17:58:58
package at.guigu.test; import at.guigu.mapper.BrandMapper; import at.guigu.pojo.Brand; 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.HashMap; import java.util.List; import java.util.Map; public class MyBatisTest { private static BrandMapper getBrandMapper() throws IOException { //1 加载核心配置文件,获取`SqlSessionFactory`对象 //1.1 配置mybatis-config.xml文件路径,由于该文件直接在resources目录下,所以直接写文件名即可 String resource = "mybatis-config.xml"; //1.2 利用Resources类中的静态方法将配置文件加载到内存 InputStream inputStream = Resources.getResourceAsStream(resource); //1.3 获取SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2 获取SqlSession对象,执行SQL语句 //2.1 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //2.2 获取Mapper接口UserMapper的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); return brandMapper; } //多条件查询方式一:散装参数接收 @Test public void testSelectByCondition() throws IOException { //接收前端传回的多条件参数 int status = 1; String companyName = "华为"; String brandName = "华为"; //处理参数 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; //获取Mapper接口对象 BrandMapper brandMapper = getBrandMapper(); //2.3 执行sql语句 List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName); System.out.println(brands); } //多条件查询方式二:对象参数接收 @Test public void testSelectByConditionTwo() throws IOException { //接收前端传回的多条件参数 int status = 1; String companyName = "华为"; String brandName = "华为"; //处理参数 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; //将多条件参数封装到对象中 Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName); //获取Mapper接口对象 BrandMapper brandMapper = getBrandMapper(); //2.3 执行sql语句 List<Brand> brands = brandMapper.selectByCondition(brand); System.out.println(brands); } //多条件查询方式三:Map集合参数接收 @Test public void testSelectByConditionThree() throws IOException { //接收前端传回的多条件参数 int status = 1; String companyName = "华为"; String brandName = "华为"; //处理参数 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; //将多条件参数封装到对象中 Map map = new HashMap(); map.put("status", status); map.put("companyName", companyName); map.put("brandName", brandName); //获取Mapper接口对象 BrandMapper brandMapper = getBrandMapper(); //2.3 执行sql语句 List<Brand> brands = brandMapper.selectByCondition(map); System.out.println(brands); } }