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

相关推荐
XiaoyuEr_66888 分钟前
maven构件子模块步骤及注意事项
java·前端·maven
drebander10 分钟前
Maven 项目的基本结构
java·maven
上海拔俗网络24 分钟前
“AI智能分析综合管理系统:企业管理的智慧中枢
java·团队开发
不听话的小耳朵37 分钟前
Tag注解
java·junit
m0_7482304439 分钟前
Java进阶学习之路
java·开发语言·学习
肥学1 小时前
面试篇——Java基础重要知识点 continue return break的不同
java·面试
程序员徐师兄1 小时前
Java 基于微信小程序的高校失物招领平台小程序(附源码,文档)
java·微信小程序·小程序·失物招领小程序·高校失物招领小程序
DEARM LINER2 小时前
RabbitMQ 可靠性投递
java·分布式·后端·rabbitmq·ruby
kfepiza2 小时前
Springboot如何使用面向切面编程AOP?
java·spring boot·后端
fly spider3 小时前
JVM执行流程与架构(对应不同版本JDK)
java·jvm·架构