欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例

 更新時(shí)間:2020年06月15日 14:52:38   作者:平凡的L同學(xué)  
這篇文章主要介紹了MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

需求:查出給定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> 

關(guān)于foreach標(biāo)簽,有幾個(gè)屬性應(yīng)該注意一下:

  • collection:指定要遍歷的集合: 
  • list類型的參數(shù)會(huì)特殊處理封裝在map中,map的key就叫l(wèi)ist 
  • item:將當(dāng)前遍歷出的元素賦值給指定的變量 
  • separator:每個(gè)元素之間的分隔符 
  • open:遍歷出所有結(jié)果拼接一個(gè)開始的字符 
  • close:遍歷出所有結(jié)果拼接一個(gè)結(jié)束的字符 
  • index:索引。遍歷list的時(shí)候是index就是索引,item就是當(dāng)前值 
  • 遍歷map的時(shí)候index表示的就是map的key,item就是map的值 
  • #{變量名}就能取出變量的值也就是當(dāng)前遍歷出的元素 

測(cè)試方法:

@Test 
  public void testDynamicSqlTest() throws IOException{ 
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); 
    //1、獲取到的SqlSession不會(huì)自動(dòng)提交數(shù)據(jù) 
    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標(biāo)簽也可以實(shí)現(xiàn)實(shí)現(xiàn)批量插入(刪除)數(shù)據(jù):

這里以批量插入數(shù)據(jù)為例:

<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> 

對(duì)應(yīng)的接口:

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

測(cè)試方法

@Test 
  public void testBatchSave() throws IOException{ 
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); 
    //1、獲取到的SqlSession不會(huì)自動(dòng)提交數(shù)據(jù) 
    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(); 
    }  
  } 

到此這篇關(guān)于MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例的文章就介紹到這了,更多相關(guān)MyBatis動(dòng)態(tài)SQL foreach批量插入內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論