mybatis 第九节 动态sql

mybatis 第九节 动态sql

  • if  where
  • choose (when, otherwise)
  • trim ( set)
  • foreach

1、if where 实现

		/* selecttest */
	Employee emp =dao.selecttest(1, "%dgxnew%66");
      System.out.println(emp);

或者 用where 去掉and

 <select id="selecttest" resultMap="zidiyiMap">  
 select * from employee  
<where>
 <if test="id !=null and id !=0 ">
id=#{id} 
 </if>
 <if test="lastName !=null">
last_Name like #{lastName} 
 </if>
</where>  
  </select>

2、choose whens 实现

 <select id="selecttest" resultMap="zidiyiMap">  
    select * from employee where 1=1  
    <choose>
    <when test="id !=null and id !=0">
      and id=#{id} 
    
    </when>
    <when test="lastName !=null">
    and last_Name like #{lastName} 
 </when>        
    </choose>   
   
     </select> 

二、set用法

		/* update set 标签去除后面的, */
//		 Employee emp =new Employee();
//		 emp.setId(6); 
//		 emp.setLastName(null);
//		 emp.setEmail("adddf@126.com");
//		 
//		 dao.updateEmp(emp); 
//		 session.commit();
//		 session.close();

 

  <select id="updateEmp" resultMap="zidiyiMap" >
    UPDATE EMPLOYEE 
    <set>
    <if test="lastName !=null and id !=0"> 
    last_name =#{lastName},      
    </if> 
    <if test ="email !=null">
    email = #{email}
    
    </if>
    </set>
    WHERE ID=#{id}
  </select>

三、foreach用法

	public List<Employee> selectempsById(List<Integer> list);
		List<Integer> list =new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(6);
		List<Employee> lists =dao.selectempsById(list);		
		System.out.print(lists);
		
  <select id="selectempsById" resultMap="zidiyiMap">
  SELECT * FROM employee WHERE ID IN 
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值