1. 程式人生 > >Mybatis學習筆記14 - 動態sql之foreach標簽

Mybatis學習筆記14 - 動態sql之foreach標簽

tis integer eem space reac aslist com ann 處理

示例代碼:

接口定義:
package com.mybatis.dao;

import com.mybatis.bean.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {
    //查詢員工id在給定集合中的
    public List<Employee> getEmpsByConditionForeach(@Param("ids") List<Integer> ids);
}


mapper定義:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.dao.EmployeeMapper">
    <!--
        collection:指定要遍歷的集合:
            list類型的參數會特殊處理封裝在map中,map的key就叫list
        item:將當前遍歷出的元素賦值給指定的變量
        separator:每個元素之間的分隔符
        open:遍歷出所有結果拼接一個開始的字符
        close:遍歷出所有結果拼接一個結束的字符
        index:索引。遍歷list的時候index就是索引,item就是當前值
                      遍歷map的時候index表示的就是map的key,item就是map的值
        #{變量名} 取出變量的值也就是當前遍歷出的元素
      -->
    <select id="getEmpsByConditionForeach" resultType="com.mybatis.bean.Employee">
        select * from tbl_employee
        <foreach collection="ids" item="item_id" separator=","
                 open="where id in(" close=")">
            #{item_id}
        </foreach>
    </select>
</mapper>


測試代碼:
package com.mybatis.demo;

import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class MyTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void test() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession(true);
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            List<Employee> emps = mapper.getEmpsByConditionForeach(Arrays.asList(1, 6, 8));
            for (Employee emp : emps) {
                System.out.println(emp);
            }
        } finally {
            openSession.close();
        }
    }
}

Mybatis學習筆記14 - 動態sql之foreach標簽