![](/img/trans.png)
[英]How to dynamically select a resultMap and append an incrementing integer value to a “non-existent” column in MyBatis?
[英]Passing a non-column parameter in a MyBatis ResultMap to a nested select
我在我的域模型中有一个一对多的关系,我基本上想读取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
}
现在我想用特定颜色的Bars
读取具有特定名称的Foos
:
public interface FooRepository {
public List<Foo> selectFoosWithBars(String name, String color);
}
我的 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>
一切正常,除了selectBars
SELECT 中的#{color}
参数。 我可以在第一个selectFoosWithBars
使用 color 参数而没有任何问题,但是如何将参数传递给嵌套的selectBars
?
请注意,我目前正在尝试对 SQL 进行性能调整,但不幸的是,在第一个 SELECT 中简单地加入bars
和foos
表并不是一种选择。
这可以通过在主查询中使用带有人工列的技巧并适当配置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>
然后使用f_color
列将参数传递给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>
如果我正确阅读了这篇文章,那么我在这里讨论的解决方案相同:
应该管用。 您可以通过从selectFoosWithBars
选择selectFoosWithBars
其作为列属性selectFoosWithBars
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.