LoginSignup
5
1

More than 3 years have passed since last update.

【MyBatis】List<Map<>> 入れ子をMapperパラメータとして渡す

Last updated at Posted at 2019-07-24

MyBatis のMapperパラメータに入れ子で渡したい!

  • Mapは key, value で可能
  • Listは 普通に入れ子で可能

環境

開発PC: Windows 10
STS: 4
mybatis:3.2.5
mybatis-spring:1.2.2
Java: 8

公式ドキュメント

http://www.mybatis.org/mybatis-3/ja/dynamic-sql.html
入れ子の説明は特になし

SQL用意

  • マッパー:xml
SampleMapper.xml
  <select id="selectTestMapList" resultMap="BaseResultMap">
  SELECT
    sample.*
  FROM
    sample
  WHERE
    sample.id IN
    <foreach item="internalMap" collection="nestedMapList">
        <foreach item="value" index="key" collection="internalMap"  open="(" separator="," close=")">
            #{value}
        </foreach>
    </foreach>
  </select>

java定義

  • マッパー:java
SampleMapper.java
List<Sample> selectTestMapList(@Param("nestedMapList") List<Map<String, Integer>> nestedMapList);

実行してみる

TestMapperExecutor.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/sample/spring/test-context.xml"})
public class TestMapperExecutor {

    @Autowired
    private SampleMapper sampleMapper;

    @Test
    public void test() {
        List<Map<String, Integer>> nestedMapList = new CopyOnWriteArrayList<>();
        Map<String, Integer> internalMap = new ConcurrentHashMap<>();
        internalMap.put("iKey", 1);
        nestedMapList.add(internalMap);

        List<Sample> result = null;
        try {

            result = sampleMapper.selectTestMapList(nestedMapList);
        }
        catch (Throwable t) {
            t.printStackTrace();
        }

    }

}

以上、お疲れ様でした!

5
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1