单条件动态查询
**从多个条件中选择一个
*choose(when,otherwise):选择,类似于Java中的switch语句
步骤一:创建方法类
/**
* 单条件动态查询
* @param brand
* @return
*/
List<Brand> selectByConditionSingle(Brand brand);
步骤二:书写对应的select语句
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
where
<choose><!--choose相当于java里的switch,when相当于case,test是判断-->
<when test="status != null">
status = #{status}
</when>
<when test="companyName != null and companyName != ''">
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != ''">
brand_name like #{brandName}
</when>
</choose>
<otherwise>
1 = 1
</otherwise>//保底的,如何用户什么也没选,不至于系统崩溃
</select>
步骤三:修改测试类
//单条件动态查询
public void testselectByConditionSingle() 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);*/
//1. 获取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.selectByConditionSingle(brand);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
修改的地方:1.参数brand设置
2.执行方法调用打印brand
牛逼的地方就是:它根据status这一个关键字进行了动态的模糊查询
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏