亲宝软件园·资讯

展开

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

平凡的L同学 人气: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标签,有几个属性应该注意一下:

测试方法:

@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){ 
          Systemoutprintln(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(); 
    }  
  } 

加载全部内容

相关教程
猜你喜欢
用户评论