【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等)。

相关推荐
a程序小傲3 分钟前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先
仙俊红5 分钟前
spring的IoC(控制反转)面试题
java·后端·spring
阿湯哥6 分钟前
AgentScope Java 集成 Spring AI Alibaba Workflow 完整指南
java·人工智能·spring
小楼v16 分钟前
说说常见的限流算法及如何使用Redisson实现多机限流
java·后端·redisson·限流算法
与遨游于天地29 分钟前
NIO的三个组件解决三个问题
java·后端·nio
czlczl200209251 小时前
Guava Cache 原理与实战
java·后端·spring
yangminlei1 小时前
Spring 事务探秘:核心机制与应用场景解析
java·spring boot
记得开心一点嘛2 小时前
Redis封装类
java·redis
lkbhua莱克瓦242 小时前
进阶-存储过程3-存储函数
java·数据库·sql·mysql·数据库优化·视图
计算机程序设计小李同学2 小时前
基于SSM框架的动画制作及分享网站设计
java·前端·后端·学习·ssm