如何通过MyBatis动态SQL实现修改、where+if/trim+if/if查询、foreach查询、choose查询、分页查询?

本文详细介绍了MyBatis框架中动态SQL的多种使用方法,包括set+if、trim+if、where+if、foreach查询等技巧,以及choose选择结构的应用场景。通过具体的XML映射文件示例,展示了如何根据不同业务需求灵活构造SQL语句。

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

    修改

 <!--    方法1:修改  set+if -->
      <update id="updatee" parameterType="User">
     
         update smbms_user 
     <set><!--  动态set元素可以剔除 , -->
	     <if test="userCode!=null">userCode=#{userCode},</if>
	     <if test="userName!=null">userName=#{userName},</if>
	     <if test="userPassword!=null">userPassword=#{userPassword},</if>
	     <if test="gender!=null">gender=#{gender},</if>
	     <if test="birthday!=null">birthday=#{birthday},</if>
	     <if test="phone!=null">phone=#{phone},</if>
	     <if test="address!=null">address=#{address},</if>
	     <if test="userRole!=null">userRole=#{userRole},</if>
	     <if test="modifyBy!=null">modifyBy=#{modifyBy},</if>
	     <if test="modifyDate!=null">modifyDate=#{modifyDate}</if>
     </set>
        where id=#{id}
     </update>
      
     
     
     <!--  方法2:修改  trim +if  -->
<!--      <update id="updatee" parameterType="User">
          update smbms_user
          <trim prefix="set" suffixOverrides="," suffix="where id=#{id}">
	          <if test="userCode!=null">userCode=#{userCode},</if>
		     <if test="userName!=null">userName=#{userName},</if>
		     <if test="userPassword!=null">userPassword=#{userPassword},</if>
		     <if test="gender!=null">gender=#{gender},</if>
		     <if test="birthday!=null">birthday=#{birthday},</if>
		     <if test="phone!=null">phone=#{phone},</if>
		     <if test="address!=null">address=#{address},</if>
		     <if test="userRole!=null">userRole=#{userRole},</if>
		     <if test="modifyBy!=null">modifyBy=#{modifyBy},</if>
		     <if test="modifyDate!=null">modifyDate=#{modifyDate},</if>
          
          </trim>
    
     </update> -->

查where+if/trim+if/if查询

<!--  查:方法一 where+if
 按条件查询得到用户表列表,需要显示指定字段,并显示用户角色(中文表述) 
	<select id="getUserList"  resultType="User">
		select * from smbms_user  
		 1.where 元素只会在至有一个子元素的条件返回sql子句的情况下才会插入where
		     2.若语句的开头是and  or  ,where元素可以将他们去掉
		
	<where>
		    下面条件是可以选择的test:写你的条件判断
		 <if test="userName!=null and userName=''">
		      and u.userName like CONCAT('%',#{userName},'%')
		</if>
		<if test="userRole!=null">
		     and u.userRole=#{userRole}
		</if>
	</where> 
	</select>

-->
	
	
	<!-- 查:方法二 trim+if   按条件查询得到用户表列表,需要显示指定字段,并显示用户角色(中文表述) -->
	<select id="getUserList"  resultType="User">
		select * from smbms_user  
	
	<trim prefix="where" prefixOverrides="and | or">
		   
		 <if test="userName!=null and userName=''">
		      and u.userName like CONCAT('%',#{userName},'%')
		</if>
		<if test="userRole!=null">
		     and u.userRole=#{userRole}
		</if>
	</trim> 
	</select>
	
	<!-- 
	    特例:单纯if
	<select id="getUserList"  resultMap="userList">
		select u.*,r.roleName from smbms_user u,smbms_role r
		where u.userRole=r.id
		 下面条件是可以选择的test:写你的条件判断
		<if test="userRole!=null">
		     and u.userRole=#{userRole}
		</if>
		<if test="userName!=null and userName=''">
		     and u.userName like CONCAT('%',#{userName},'%')
		</if>
		
	</select>
	 -->
foreach查询
item表示集合中每一个元素进行迭代时的别名,可以随便写,但是要和#{}中的值保持一致
index用于表示在迭代过程中,每次迭代到的位置,
open表示该语句以什么开始,
separator表示在每次进行迭代之间以什么符号作为分隔 符,
close表示以什么结束

     <!--  指定用户角色为array(1-n个),获取这些用户角色下的用户列表信息-->
     <select id="getUserByRoled_array" resultMap="userMapArray">
     		select * from smbms_user 
     		where userRole in 
     		<foreach collection="array" item="rolelds" open="(" separator="," close=")">
     		      #{rolelds}
     		</foreach>
     		
     </select>
     
     <resultMap type="User" id="userMapArray">
          <id property="id" column="id"/>
          <result property="userCode" column="userCode"/>
           <result property="userName" column="userName"/>
     </resultMap>
     
      <!--  指定用户角色为list(1-n个),获取这些用户角色下的用户列表信息-->
     <select id="getUserByRoled_list" resultMap="userMapArray">
     	select * from smbms_user 
     	where userRole in
     	<foreach collection="list" item="roleList" open="(" separator="," close=")">
     		      #{roleList}
     	</foreach>
     	
     </select>
  <!-- 传入参数为Map集合 item的值要和#{}保持一致; collection的值要是 map中的key值 -->
     <select id="getUserByMap" resultMap="userMapArray">
        select * from smbms_user 
        where gender=#{gender}
        and userRole in  
        <foreach collection="roleIds" item="roleMap" open="(" separator="," close=")">
        	#{roleMap}
        </foreach>
     </select>
	//多个参数   Map
	public List<User> getUserByMap(Map<String,Object> conditionMap);

      @Test
		  		public void test17() {
			    	SqlSession sqlSession=null;
			    	List<User> userList=new ArrayList<User>();
			    	Map<String,Object> conditionMap=new HashMap<String,Object>();
                                //in里面的值们可以理解成是 一个Integer类型的集合 这个集合 是Map集合中一个集合元素
			    	 List<Integer> roleList=new ArrayList<Integer>();
			    	 roleList.add(2);
			    	 roleList.add(3);
			    	 conditionMap.put("gender", 1);
			    	 conditionMap.put("roleIds", roleList);
			    	 
			    	try{
			    		sqlSession=MyBatisUtil.createSqlSession();
				    	userList=sqlSession.getMapper(UserMapper.class).getUserByMap(conditionMap);
			    	}catch(Exception e){
			    		e.printStackTrace();
			    	}finally{
			    		MyBatisUtil.closeSqlSession(sqlSession);
			    	}
			    	
			      for(User user : userList){
			    	  logger.debug(user.getUserCode()+"----"+user.getUserName()+"===="+user.getUserCode()+"__--"+user.getUserRole()+"---"+user.getGender());
			    	   
			      }
			      
			      
	      
          }
choose查询
  <!-- choose -->
       <select id="getUserList_choose" resultType="User">
            select * from smbms_user where 1=1
            <choose>
            <!--当满足when 里条件的时候,执行里面的sql语句,执行完毕就跳出choose  -->
            	<when test="userName!=null and userName!=''">
            			and userName like CONCAT('%',#{userName},'%')
            	</when>
            	<when test="userCode!=null and userCode!=''">
            			and userName like CONCAT('%',#{userCode},'%')
            	</when>
            	<otherwise>
            	<!-- 当条件不满足的时候,执行 otherwise里的代码-->
            	     and YEAR(creationDate)=YEAR(NOW())
            	</otherwise>
            </choose>
       </select>


	//choose 选择
	public List<User> getUserList_choose(@Param("userName")String userName,
			                              @Param("userCode")String userCode,
			                              @Param("userRole")Integer roleId,
			                              @Param("creationDate")Date creationDate);


 @Test
		  		public void test18() {
			    	SqlSession sqlSession=null;
			    	List<User> userList=new ArrayList<User>(); 
			    	try{
			    		sqlSession=MyBatisUtil.createSqlSession();
			    		String userName="";
			    		Integer roleId=null;
			    		String userCode="";
			    		Date creationDate=new SimpleDateFormat("yyyy-MM-dd").parse("2017-06-06");
				    	userList=sqlSession.getMapper(UserMapper.class).getUserList_choose(userName, userCode, roleId, creationDate);
			    	}catch(Exception e){
			    		e.printStackTrace();
			    	}finally{
			    		MyBatisUtil.closeSqlSession(sqlSession);
			    	}
			    	
			      for(User user : userList){
			    	  logger.debug(user.getUserCode()+"----"+user.getUserName()+"===="+user.getUserCode()+"__--"+user.getUserRole()+"---"+new SimpleDateFormat("yyyy-MM-dd").format(user.getCreationDate()));
			    	   
			      }
			      
			      
	      
        }   
分页查询
 <!-- 分页 -->
       <select id="getUserListeses" resultMap="userList">
          select u.*,r.roleName
          from smbms_user u,smbms_role r
          where u.userRole=r.id
          <if test="userRole!=null">
          and u.userRole=#{userRole}
          </if>
          <if test="userName!=null and userName!=''">
          and u.userName like CONCAT('%',#{userName},'%')
        
          </if>                               
            order by creationDate DESC limit ${from},${pageSize}
       </select>
       
       <resultMap type="User" id="userList">
       			<result property="id" column="id"/>
       			<result property="userCode" column="userCode"/>
       			<result property="userName" column="userName"/>
       			<result property="phone" column="phone"/>
       			<result property="userRole" column="userRole"/>
       			<result property="userRoleName" column="roleName"/>
       </resultMap>

//分页:
	public List<User> getUserListeses(@Param("userName")String userName,
			                          @Param("userRole")Integer roleId,
			                          @Param("from")Integer currentPageNo,
			                          @Param("pageSize")Integer pageSize);

      @Test
		  		public void test19() {
			    	SqlSession sqlSession=null;
			    	List<User> userList=new ArrayList<User>(); 
			    	try{
			    		sqlSession=MyBatisUtil.createSqlSession();
			    		String userName="";
			    		Integer roleId=null;
			    		Integer pageSize=5;
			    		//数据库下标是从0开始的          (页数-1)*pageSize
			    		Integer currentPageNo=0;  
			    		
				    	userList=sqlSession.getMapper(UserMapper.class).getUserListeses(userName, roleId, currentPageNo, pageSize);
			    	}catch(Exception e){
			    		e.printStackTrace();
			    	}finally{
			    		MyBatisUtil.closeSqlSession(sqlSession);
			    	}
			    	
			      for(User user : userList){
			    	  logger.debug(user.getId()+"=="+user.getUserCode()+"=="+user.getUserRoleName()+"=="+user.getPhone());
			    	   
			      }
			      
			      
	      
      }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟空非空也

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值