How to pass parameters in MyBatis subquery?

There are two ways to pass parameters to subqueries in MyBatis.

  1. I need to finish my homework before I can go out with my friends.
  2. I need to go grocery shopping.
  3. 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);
  1. for each
  2. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds