mybatis08动态SQL

本文详细介绍MyBatis中动态SQL的使用技巧,包括if标签、SQL片段和foreach的运用,有效解决查询条件多变的问题,提升代码复用性和可读性。

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

mybatis08动态SQL

在很多情况下,查询条件可能会有很多变化,在mybatis中也会有相应的解决方式

if标签

if标签用于判断单个查询条件是否存在

具体实现
  • mapper.xml配置

      <!-- 通过name和age模糊查找记录 -->
      <select id="selectUserByNameAndAge" parameterType="user" resultType="user">
      	select * from user
      	<!-- where可自动去除拼接中的and -->
      	<where>
      		<if test="userAge != 0">
      			and userAge = #{userAge}
      		</if>
      		<if test="userName != null">
      			and userName like '%${userName}%'
      		</if>
      	</where>
      </select>
    
  • 配置相关接口

      public List<User> selectUserByNameAndAge(User user) throws Exception;
    
  • 测试代码实现

      @Test
      public void testSelectUserByNameAndAge() throws Exception {
      	
      	SqlSession sqlSession = sqlSessionFactory.openSession();
      	
      	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      	
      	User user = new User();
      	
      	user.setUserAge(18);
      	user.setUserName("小亮");
      	
      	List<User> list = userMapper.selectUserByNameAndAge(user);
      	
      	System.out.println(list);
      	
      }
    
总结

测试是成功的,但是那部分where的代码重复度很高


SQL片段

在mybatis中,仍有相关解决办法

具体实现
  • 配置mapper.xml

      <!-- 动态SQL -->
      <!-- 用于拼接user相关的SQL:
      id:唯一标识符
       -->
      <sql id="user_where">
      	<if test="userAge != 0">
      		and userAge = #{userAge}
      	</if>
      	<if test="userName != null">
      		and userName like '%${userName}%'
      	</if>
      </sql>
    
      <!-- 通过name和age模糊查找记录 -->
      <select id="selectUserByNameAndAge" parameterType="user" resultType="user">
      	select * from user
      	<!-- where可自动去除拼接中的and -->
      	<where>
      		<!-- 若动态SQL在其它mapper.xml中
      		refid="namespase.id"
      		 -->
      		<include refid="user_where"></include>
      	</where>
      </select>
    

foreach

foreach实现重复类似的查询条件

具体实现
  • 配置mapper.xml

      <!-- 举例:and (id=1 or id=10 or id=8)
      collection: model中相应集合属性
      			例如User中有:
      				private List<Integer> ids;
      item: 遍历时返回值,建议与数据库字段对应
      open: 拼接前片段
      close: 拼接后片段
      separator: 拼接中间片段
       -->
      <foreach collection="ids" item="id" open="and (" close=")" separator="or">
      	id = #{id}
      </foreach>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值