How to pass parameters in MyBatis subquery?
There are two ways to pass parameters to subqueries in MyBatis.
- I need to finish my homework before I can go out with my friends.
- I need to go grocery shopping.
- type of parameter
<select id="getParentsByChildId" parameterType="java.lang.Integer" resultType="Parent">
SELECT * FROM parent WHERE id IN (
SELECT parent_id FROM child WHERE id = #{childId}
)
</select>
Pass the childId parameter when calling the subquery.
List<Parent> parents = sqlSession.selectList("getParentsByChildId", childId);
- for each
- for each
<select id="getParentsByChildIds" parameterType="java.util.List" resultType="Parent">
SELECT * FROM parent WHERE id IN (
<foreach collection="childIds" item="childId" separator=",">
SELECT parent_id FROM child WHERE id = #{childId}
</foreach>
)
</select>
Pass the childIds parameter when calling the subquery.
List<Integer> childIds = new ArrayList<>();
childIds.add(1);
childIds.add(2);
List<Parent> parents = sqlSession.selectList("getParentsByChildIds", childIds);
This allows passing the values in childIds to the subquery and returning a list of parent records that meet the criteria.