将 MyBatis ResultMap 中的非列参数传递给嵌套选择

Ste*_*erl 2 java sql mybatis

我在我的域模型中有一个一对多的关系,我基本上想要阅读Foos和过滤的集合,Bars其中包含一个 MyBatis select 语句,使用嵌套选择Bars.

解释一下:我的领域模型类看起来或多或少是这样的(真正的领域模型当然更复杂,但我的问题归结为这个):

public class Foo {
   private String name;
   private Set<Bar> bars;
   // getters and setters omitted
}

public class Bar {
   private String color;
   // getters and setters omitted
}
Run Code Online (Sandbox Code Playgroud)

现在我想FoosBars特定颜色的特定名称阅读:

public interface FooRepository {
  public List<Foo> selectFoosWithBars(String name, String color);
}
Run Code Online (Sandbox Code Playgroud)

我的 MyBatis XML Mapper 文件的相关部分如下所示:

<select id="selectFoosWithBars" resultMap="fooResult">
   SELECT f.id f_id, f.name f_name FROM foos f WHERE f.name = #{name}
</select>

<select id="selectBars" resultMap="barResult">
   SELECT b.color b_color FROM bars b
   JOIN foos f ON (b.f_id = #{id})
   WHERE b.color = #{color}
</select>

<resultMap id="fooResult" type="Foo">
   <result property="name" column="f_name">
   <collection property="bars" select="selectBars" column="f_id" />
</resultMap>

<resultMap id="barResult" type="Bar">
   <result property="color" column="b_color" />
</resultMap>
Run Code Online (Sandbox Code Playgroud)

一切都很好,除了SELECT 中的#{color}参数selectBars。我可以在第一个中使用 color 参数selectFoosWithBars而没有任何问题,但是如何将参数传递给嵌套的selectBars

请注意,我目前正在尝试对 SQL 进行性能调整,但不幸的是,在第一个 SELECT 中简单地加入barsfoos表并不是一种选择。

Rom*_*val 5

这可以通过在主查询中使用带有人工列的技巧并column适当地配置参数来实现。

这是列属性文档的相关部分:

数据库中的列名,或保存将作为输入参数传递给嵌套语句的值的别名列标签。

将具有颜色值的人工列添加到主查询:

<select id="selectFoosWithBars" resultMap="fooResult">
   SELECT f.id f_id, f.name f_name, #{color} f_color
   FROM foos f WHERE f.name = #{name}
</select>
Run Code Online (Sandbox Code Playgroud)

然后使用f_colorcolumn 将参数传递给selectBars

<select id="selectBars" resultMap="barResult">
   SELECT b.color b_color FROM bars b
   JOIN foos f ON (b.f_id = #{id})
   WHERE b.color = #{color}
</select>

<resultMap id="fooResult" type="Foo">
   <result property="name" column="f_name">
   <collection property="bars" select="selectBars" column="{id=f_id,color=f_color}" />
</resultMap>
Run Code Online (Sandbox Code Playgroud)