Spring之MyBatis——动态sql语句

本文介绍了在Spring中使用MyBatis进行动态SQL操作的方法,重点讲解了if、where、set和foreach元素的用法。通过这些元素,可以方便地根据条件动态拼接SQL语句,例如在where子句中根据条件过滤,用set更新指定列,以及使用foreach构建IN条件。示例展示了如何使用foreach元素遍历集合并生成IN条件的SQL片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.jd.userInfo.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.jd.vo.UserInfo;

public interface IUserInfoDao {
	
	List<UserInfo> select(@Param("name")String name,@Param("mobile")String mobile);
	
	boolean delete(@Param("ids")int [] ids);
	
	boolean update(@Param("id")int id,@Param("name")String name,@Param("mobile")String mobile);
}

 

利用动态 SQL可以很方便地根据不同条件拼接 SQL 语句

if

常用于根据条件拼接where 子句。

where

只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句;而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。

 

	<select id="select" resultType="com.jd.vo.UserInfo">
		select * from user_info 
		<!--where标签相当于where 1=1  -->
		<where>
			<if test="name!=null and name!=''">
				and name like #{name}
			</if>
			<if test="mobile!=null">
				and mobile = #{mobile}
			</if>
		</where> 
	</select>

set

set 元素可以用于动态包含需要更新的列,而删掉无关的逗号

	<update id="update">
		update user_info 
		<set>
			<if test="name!=null">
				name=#{name},
			</if>
			<if test="mobile!=null">
				mobile=#{mobile},
			</if>
		</set>
		where id=#{id}
	</update>

 

foreach

foreach元素用于对一个集合进行遍历,构建 IN 条件语句时常用该元素;foreach 元素允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量,也允许指定开头与结尾的字符串以及在迭代结果之间放置分隔符。

 

	<delete id="delete">
		delete from user_info where id in
		<foreach item="id" collection="ids" open="(" separator="," close=")">
			#{id}
		</foreach>
	</delete>

 

<select id="selectPostIn" resultType="domain.blog.Post">

  SELECT * FROM POST P

  WHERE ID in

  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">

        #{item}

  </foreach>

</select>

 注意:可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数;当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素;当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

public static void main(String[] args){
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			SqlSession sqlSession = sqlSessionFactory.openSession();
			IUserInfoDao userInfoDao = sqlSession.getMapper(IUserInfoDao.class);
		
			for(UserInfo ui:userInfoDao.select("%k%","13721863138")) {
				System.out.println(ui);
			}
			
			System.out.println(userInfoDao.update(5,"Lucy",null));
			//sqlSession.commit();
			sqlSession.close();
		} catch(IOException e){
			e.printStackTrace();
		}

	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值