【Java】MyBatis动态SQL

在MyBatis中使用动态SQL语句。

动态SQL是指根据参数数据动态组织SQL的技术。

生活中的案例:

在京东上买东西时,用户搜索商品,可以选择筛选条件,比如品牌,价格,材质等,也可以不使用筛选条件。这时候后台需要写多个查询模块吗?其实不需要,这时候可以用动态SQL语句,使用if标签决定在什么条件下要SQL语句要包含的内容。

if标签:

xml 复制代码
<if test="">  
	...
</if>

这个标签的作用可以理解为C++中的 #if ... #endif

示例:

xml 复制代码
<select id="selectDynamicSQL" parameterType="java.util.Map" resultType="com.hust.mybatis.entity.Goods">  
    select * from t_goods  
    where   
        <if test="categoryId != null">  <!--如果参数中:categoryId != null-->  
            category_id = #{categoryId} <!--则sql语句包含这句话-->  
        </if>  
        <if test="currentPrice != null">  
            and current_price &lt; #{currentPrice}  
        </if>  
</select>

可以在MyBatis中正常使用

java 复制代码
@Test  
public void testDynamicSQL() throws Exception {  
	SqlSession sqlSession = null;  
	try {  
		sqlSession = MyBatisUtils.openSession();  
//            Map param = new HashMap();  
		Map<String, Object> param = new HashMap<String, Object>();  
		param.put("categoryId", 44);  // 查询条件  
		param.put("currentPrice", 500);  
		
		List<Goods> list = sqlSession.selectList("com.hust.mybatis.entity.Goods.selectDynamicSQL", param);  
		for (Goods g : list) {  
			System.out.println(g.getTitle() + ": 【" + g.getCurrentPrice() + "】 -- " + g.getGoodsId());  
		}  
	} catch (Exception e) {  
		throw new RuntimeException(e);  
	} finally {  
		if (sqlSession != null) MyBatisUtils.closeSession(sqlSession);  
	}  
}

如果出现了报错,请检查一下这几个if标签有没有用逻辑运算符连接(and,or等)。

相关推荐
写不出来就跑路几秒前
WebClient与HTTPInterface远程调用对比
java·开发语言·后端·spring·springboot
Cyanto6 分钟前
深入MyBatis:CRUD操作与高级查询实战
java·数据库·mybatis
麦兜*44 分钟前
Spring Boot 集成Reactive Web 性能优化全栈技术方案,包含底层原理、压测方法论、参数调优
java·前端·spring boot·spring·spring cloud·性能优化·maven
天上掉下来个程小白1 小时前
MybatisPlus-06.核心功能-自定义SQL
java·spring boot·后端·sql·微服务·mybatisplus
知了一笑1 小时前
独立开发第二周:构建、执行、规划
java·前端·后端
今天背单词了吗9802 小时前
算法学习笔记:17.蒙特卡洛算法 ——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·笔记·考研·算法·蒙特卡洛算法
Dcs2 小时前
从 C 到 Rust:一位开发者的 `tmux` 全面移植之旅
java
Maybyy2 小时前
力扣242.有效的字母异位词
java·javascript·leetcode
小小寂寞的城3 小时前
JAVA观察者模式demo【设计模式系列】
java·观察者模式·设计模式
探索java3 小时前
Java并发编程中的StampedLock详解:原理、实践与性能优化
java·stampedlock