• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

MyBatis动态SQL foreach标签实现批量插入的方法示例

mybatis 搞代码 4年前 (2022-01-09) 16次浏览 已收录 0个评论

需求:查出给定id的记录:

<select id="getEmpsByConditionForeach" resultType="comtestbeansEmployee"> 
    SELECT * FROM tb1_emplyee WHERE id IN 
    <foreach collection="list" item="item_id" separator="," open="(" close=")"> 
      #{item_id} 
    </foreach> 
</select> 

关于foreach标签,有几个属性应该注意一下:

  • collection:指定要遍历的集合: 
  • list类型的参数会特殊处理封装在map中,map的key就叫list 
  • item:将当前遍历出的元素赋值给指定的变量 
  • separator:每个元素之间的分隔符 
  • open:遍历出所有结果拼接一个开始的字符 
  • close:遍历出所有结果拼接一个结束的字符 
  • index:索引。遍历list的时候是index就是索引,item就是当前值 
  • 遍历map的时候index表示的就是map的key,item就是map的值 
  • #{变量名}就能取出变量的值也就是当前遍历出的元素 

测试方法:

@Test 
  public void testDynamicSqlTest() throws IOException{ 
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); 
    //1、获取到的SqlSession不会自动提交数据 
    SqlSession openSession = sqlSessionFactoryopenSession(); 
    try 
    { 
        EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); 
        /*Employee employee=new Employee(1,"lili",null,"1");*/ 
        List<Employee> emps=mappergetEmpsByConditionForeach(ArraysasList(1,2,3,4)); 
        for (Employee e:emps){ 
          Systemoutp<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong>rintln(e); 
        } 
 
    } 
    finally { 
      openSessionclose(); 
    } 
  } 

foreach标签也可以实现实现批量插入(删除)数据:

这里以批量插入数据为例:

<insert id="addEmps"> 
    INSERT INTO tb1_emplyee(last_name,email,gender,d_id) 
    VALUES  
    <foreach collection="emps" item="emp" separator=","> 
      (#{emplastName},#{empemail},#{empgender},#{empdeptid}) 
    </foreach> 
</insert> 

对应的接口:

public void addEmps(@Param("emps")List<Employee> emps); 

测试方法

@Test 
  public void testBatchSave() throws IOException{ 
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); 
    //1、获取到的SqlSession不会自动提交数据 
    SqlSession openSession = sqlSessionFactoryopenSession(); 
    try 
    { 
      EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); 
      List<Employee> emps=new ArrayList<Employee>(); 
      empsadd(new Employee(null,"Eminem","Eminem@com","1",new Department(1))); 
      empsadd(new Employee(null,"2Pac","2Pac@com","1",new Department(1))); 
      mapperaddEmps(emps); 
      openSessioncommit(); 
    } 
    finally { 
      openSessionclose(); 
    }  
  } 

到此这篇关于MyBatis动态SQL foreach标签实现批量插入的方法示例的文章就介绍到这了,更多相关MyBatis动态SQL foreach批量插入内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MyBatis动态SQL foreach标签实现批量插入的方法示例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址