我有一个关于 Mybatis 中的映射器的问题。我有两个这样的类(class):
public class A{
private String A1;
private String A2;
private List<B> listB;
//getters and setters
.
.
.
public static class B {
private String B1;
private String B2;
//getters and setters
.
.
.
}
}
然后我有一个像这样的映射器类:
@Mapper
public interface ABMapper{
@Select("select b1,b2 from b where b.a1 = #{a1}")
public List<B> getBs(@Param("a1") String a1);
@Select ("select a1,a2 from a limit 100")
@Results({
@Result(property="a1", value = "a1"),
@Result(property="a2", value = "a2"),
@Result(property="listB", column="a1", many = @Many(select = "getBs"))
})
public List<A> getAs();
}
这工作正常,但我知道当 getAs()
执行时,getBs 运行的次数与项目的次数相同(例如限制 100)。
我想知道是否存在一种方法来运行像 select a.a1,a.a2,b.b1,b.b2 from a a inner join b b on a.a1 = b.a1
这样的查询然后Mybatis(和Java)可以将 List<A>
中的元素分组并且属性B不为空。
也许,在A类和B类中需要使用hash和equals,但我不知道。
感谢您的回答。
最佳答案
Mybatis 可以做到这一点,但前提是您使用 xml 映射。 java中注解的限制使得无法用join来映射关联:
You will notice that join mapping is not supported via the Annotations API. This is due to the limitation in Java Annotations that does not allow for circular references.
在这种情况下,映射可能如下所示:
<resultMap id="bMap" type="B">
<id property="b1" column="b1"/>
<result property="b2" column="b2"/>
</resultMap>
<resultMap id="aMap" type="A">
<id property="a1" column="a1"/>
<result property="a2" column="a2"/>
<collection property="listB" javaType="B" resultMap="bMap" columnPrefix="b_"/>
</resultMap>
<select id='getAs' resultMap='aMap'>
SELECT a.*, b.id B_id, b.b1 B_b1, b.b2 B_b2
FROM (
select *
from a
LIMIT 100
) AS a
LEFT JOIN AS b on a.a1 = b.a1
</select>
一些重要的注意事项:
A
和B
都应该有一些使用id
元素配置的标识字段。该字段中的值将用于识别对象并执行所谓的分组。对于表a
,这似乎是a1
(因为您将其用作连接字段),我在示例中使用了它。
如果有很多字段需要映射,autoMapping="true"
可能会很有用- 您需要使用左/右连接来处理表
a
中的那些在b
中没有任何内容的记录。 - 为了
LIMIT
正确地使用连接,您需要在从a
获取记录的选择上执行此操作,而不是在连接结果上执行此操作,否则您可能会得到小于如果连接b
中的 100 条以上记录,则结果中包含 100 条记录。 - 这取决于用例,但通常如果您使用
LIMIT
,则需要指定某种顺序,否则记录将以不可预测的顺序返回。 - 在旧版本的 mybatis 中,存在一个错误,要求查询中的列前缀应为大写(可能现在已修复,我不确定)。
resultMap
中的 关于java - 将结果分组到List中,List是Mybatis(Mapper)和Java中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58240990/