MyBatis案例:多条件查询
MyBatis案例:多条件查询
- 编写接口方法:Mapper接口
- 参数:所有查询条件
- 结果:
List<Brand>
- 编写SQL语句:SQL映射文件
- 执行方法,测试
SQL语句设置多个参数有三种方式:
- 散装参数:需要使用@Param("SQL中的参数占位符名称")
- 实体类封装参数:只需要保证SQL中的参数名和实体类属性名对应上,即可设置成功
- map集合:只需要保证SQL中的参数名和map集合的键的名称对应上,即可设置成功
// 测试类中多条件查询的部分代码MyBatisTest.java
@Test
public void testSelectByCondition() 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);*/
Map map = new HashMap();
map.put("status", status);
map.put("companyName", companyName);
map.put("brandName", brandName);
// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3. 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 4. 执行方法, 三种方式执行多条件查询
// List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
// List<Brand> brands = brandMapper.selectByCondition(brand);
List<Brand> brands = brandMapper.selectByCondition(map);
System.out.println(brands);
// 5. 释放资源
sqlSession.close();
}
<!--SQL映射文件中的部分代码,多条件查询语句的配置-->
<!--
条件查询
-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
</select>
- 动态条件查询:多条件查询优化。