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();
}
}
}
以上、お疲れ様でした!