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

相关推荐
QWQ___qwq18 分钟前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
识君啊44 分钟前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
月月玩代码2 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
阿珍爱上了阿强,在一个有星星的夜晚3 小时前
node后端页面性能监测分析
java·学习方法
Java程序之猿3 小时前
SpringBoot + camel+IBM MQ实现消息队列处理
java·spring boot·mybatis
z_鑫4 小时前
SpringCloud FeignClient 中 Bean 重复注册冲突解决方案解析
java·spring boot·spring cloud
孫治AllenSun4 小时前
【线程池】优化等待队列和拒绝策略
java·spring boot·spring cloud
毕设源码-邱学长5 小时前
【开题答辩全过程】以 基于Spring Boot的体育场地预约管理系统为例,包含答辩的问题和答案
java·spring boot·后端
青槿吖5 小时前
第二篇:告别XML臃肿配置!Spring注解式IOC/DI保姆级教程,从入门到真香
xml·java·开发语言·数据库·后端·sql·spring