Post

MyBatis foreach 문법

1. Array 사용

  • Controller
1
2
String[] array = {"a", "b", "c"};
demoVO.setDemoArray(array);
  • VO
1
2
3
4
5
6
7
8
9
10
11
12
public class DemoVO {

    private String[] demoArray;

    public String[] getDemoArray() {
        return demoArray;
    }

    public void setDemoArray(String[] demoArray) {
        this.demoArray = demoArray;
    }
}
  • SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="selectDemoList" resultType="com.example.demo.vo.DemoVO">
    select
        id
        , name
        , addr
    from
        table_name
    where
        id in
    <foreach collection="demoArray" item="item" index="index" open="(" close=")" separator=",">
        #{item}
    </foreach>
</select>

2. List 사용

  • Controller
1
2
3
4
5
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
demoVO.setDemoList(list);
  • VO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.List;

public class DemoVO {

    private List<String> demoList;

    public List<String> getDemoList() {
        return demoList;
    }

    public void setDemoList(List<String> demoList) {
        this.demoList = demoList;
    }
}
  • SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="selectDemoList" resultType="com.example.demo.vo.DemoVO">
    select
        id
        , name
        , addr
    from
        table_name
    where
        id in
    <foreach collection="demoList" item="item" index="index" open="(" close=")" separator=",">
        #{item}
    </foreach>
</select>
This post is licensed under CC BY 4.0 by the author.