MyBatis(五) 动态SQL

1.动态查询(动态生成Where语句):

这篇文章中叙述的功能,统一使用下表测试:

CREATE TABLE `test_order_detail_mm` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `order_id` int(20) NOT NULL,
  `goods_name` varchar(50) DEFAULT NULL,
  `single_price` decimal(19,2) DEFAULT NULL,
  `num` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

(1)我们在写SELECT语句时,有时候会遇到有不定数量个where条件,一般我们在处理时,需要动态的拼写sql语句,在Mybatis中使用动态sql,where标签来处理这个问题。

(2)配置mapper文件:

<select id="dynamicSelect" parameterType="com.vip.model.TestOrderDetailMm" resultMap="orderDetailResultMap">
	select * from test_order_detail_mm 
	<where>
		<if test="id!=0">id = #{id}</if>
		<if test="orderId!=0">AND order_id = #{orderId}</if>
		<if test="goodsName!=null">AND goods_name like ‘%${goodsName}%‘ </if>
		<if test="singlePrice!=0">AND single_price = #{singlePrice}</if>
		<if test="num!=0">AND num = #{num}</if>
	</where>
</select>

where元素的作用是会在写入where元素的地方输出一个where,并且mybatis会智能地根据if条件来输出where条件。如上例,假如orderId=0那么“AND order_id = #{orderId}”这条语句将不会输出。另外假如第一个标签id不符合,第一个where条件就变成了“AND order_id = #{orderId}”,即使这样,前面也不会加and。

(3)测试类:

	@Test
	public void dynamicSelect() {
		SqlSession session = sqlSessionFactory.openSession();
		//创建查询对象
		TestOrderDetailMm  tst = new TestOrderDetailMm();
		tst.setSinglePrice(198.5);
		tst.setNum(2);
		//执行动态查询
		List<TestOrderDetailMm> lst  = session.selectList("com.vip.mapping.TestOrderDetailMm.dynamicSelect", tst);
		System.out.println(lst);
	}

如上例中,我们只设置了2个查询条件,SinglePrice和num 两个条件,其余属性未设置。这块需要注意,对于String类型的属性,如果未set则为null,如果是int或double,未set则为0。

(4)运行结果:

DEBUG - ooo Using Connection [[email protected]]
DEBUG - ==>  Preparing: select * from test_order_detail_mm WHERE single_price = ? AND num = ? 
DEBUG - ==> Parameters: 198.5(Double), 2(Integer)
[TestOrderDetailMm [id=2, orderId=1, goodsName=衣服, singlePrice=198.5, num=2], TestOrderDetailMm [id=3, orderId=1, goodsName=衣服, singlePrice=198.5, num=2]]

如上边的运行日志,在where条件中,只有2个条件single_price和num,其余我们未设置的查询条件(属性)没有放在Where条件中。


2.动态更新(动态生成update set语句):

动态update,与动态查询类似。我们对某个属性设置值后,只update这个属性,而不会将其他属性设置成null或者0。

(1)Mapper文件:

<update id="dynamicUpdate" parameterType="com.vip.model.TestOrderDetailMm" >
	update test_order_detail_mm 
	<set>
		<if test="id!=0">id = #{id},</if>
		<if test="orderId!=0">order_id = #{orderId},</if>
		<if test="goodsName!=null">goods_name = #{goodsName}, </if>
		<if test="singlePrice!=0">single_price = #{singlePrice},</if>
		<if test="num!=0">num = #{num}</if>
	</set>
	where id = #{id}
</update>

(2)测试类:

@Test
	public void dynamicUpdate() {
		SqlSession session = sqlSessionFactory.openSession();
		//创建查询对象
		TestOrderDetailMm  tst = new TestOrderDetailMm();
		tst.setId(2);
		tst.setGoodsName("遥控车");
		//执行动态查询
		session.update("com.vip.mapping.TestOrderDetailMm.dynamicUpdate", tst);
		session.close();
	}

(3)运行结果:

DEBUG - ooo Using Connection [[email protected]]
DEBUG - ==>  Preparing: update test_order_detail_mm SET id = ?, goods_name = ? where id = ? 
DEBUG - ==> Parameters: 2(Integer), 遥控车(String), 2(Integer)

如上运行结果,我们只update了goods_name字段,没有修改其他字段。

3.实现in操作:

4.实现in操作:


5.批量插入:


6.批量删除:

时间: 2024-08-29 13:49:12

MyBatis(五) 动态SQL的相关文章

MyBatis的动态SQL详解

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力.如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号.动态 SQL 可以彻底处理这种痛苦. 通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种

Mybatis的动态Sql

基础部分可以查看我的另一篇博客:http://blog.csdn.net/elim168/article/details/40622491 MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) trim where set foreach if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择.先来看如下一个例子: Xml代码 <sele

mybatis 使用动态SQL

RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role role); public void delete(Role role); public List<Role> getRoleList(Role role); } RoleMapper.xml <?xml version="1.0" encoding="UTF-8&

MyBatis中动态SQL语句完成多条件查询

http://blog.csdn.net/yanggaosheng/article/details/46685565 MyBatis中动态SQL语句完成多条件查询 <select id="queryEmp"  resultType="cn.test.entity.Emp"> select * from emp where 1=1 <if test="deptNo!=null"> and deptno=#{deptNO} &

MyBatis 构造动态 SQL 语句

以前看过一个本书叫<深入浅出 MFC >,台湾 C++ 大师写的一本书.在该书中写道这样一句话,"勿在浮沙筑高台",这句话写的的确对啊.编程很多语言虽然相同,但是真正做还是需要认真的学习,如果只是想着按想像着来,真的是会走很多弯路,浪费很多时间. 无法使用 not in 在项目中需要使用到 not in ,想着不是很复杂,但是这个问题困扰了我个把小时,很是郁闷.自己拼接好了字符串,字符串的内容是 not in 中的各个 id 值.通过 not in 来进行 update 的

MyBatis探究-----动态SQL详解

1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不可少 <select id="getEmpsByEmpProperties" resultType="com.mybatis.entity.Employee"> select * from t_employee where 1=1 <if test=&

Mybatis系列---动态SQL

问题: 什么是动态SQL? 动态SQL有什么作用? 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误.Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach,可组合成非常灵活的SQL语句,从而提高开发人员的效率. 下述可知道这四个操作节点中的子节点都是差不多是一样的,insert和update中多了一个selectK

一分钟带你了解下MyBatis的动态SQL!

MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格.列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下. 一.if标签 if是最常用的判断语句,主要用于实现某些简单的条件选择.基本使用示例如下: <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User&quo

Mybatis的动态sql拼接语句

Mybatis的动态sql拼接语句 1.主配置文件SqlMapConfig.xml  <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE configuration         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"         "http://mybatis.org/dtd/mybatis-3-config.dtd