MyBatis集合映射小试

问题

现在项目中有个单据有三个表关系,主表、明细表、次明细表,大概关系如下面代码所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Main{
private String mtId;
private List<Sub> subs;
......
}

class Sub{
private String mtId;
private List<Bat> bats;
......
}

class Bat{
private String mtId;
......
}

之前有人最笨最笨的办法就是从数据库拉三次出来,然后再组成整个数据结构。其实本来MyBatis里面就有Collection,用起来很方便。然后我就用下面的Mapper.xml来改试了一下。

尝试

MyBatis官网已经讲了Collection的使用,很详细了。然后就自己试下看如何更爽的解决之前那个问题。MyBatis已经把配置荐mapUnderscoreToCamelCase设置成true了,这样就可以少写Entity的映射关系了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<select id="getWholeBill" resultMap="EntirBillResultMap">
SELECT
m.mt_id AS mt_id, s.mt_id AS s_mt_id, b.mt_id AS s_b_mt_it
FROM
main m
INNER JOIN
sub s ON (s.pid = m.id)
INNER JOIN
bat b ON (m.pid = s.id)
WHERE m.mt_id = #{id}
</select>

<resultMap id="EntirBillResultMap" type="Main" autoMapping="true">
<collection property="subs" columnPrefix="s_" ofType="Sub" autoMapping="true">
<collection property="bats" columnPrefix="b_" ofType="Bat" autoMapping="true">
</collection>
</collection>
</resultMap>

本来以为这样可以很好地解决我的问题,但是但是,测试的时候发现,主表和明细表好像没有group by的状态。

修改

碰到这个问题,其实查下源码可能就好解决了。但是其实我一直没有碰MyBatis的源码,所以可能查起来会很头痛。网上稍微搜了下,没有找到答案。应该是映射关系写得有问题吧。尝试了几次,觉得就是没有group by嘛,但是如果告诉MyBatis去group by哪个字段呢?好像平时写得最多的那个id标签没有用哦,太懒了,把这个都省掉。果然加上去就解决了,嗯嗯,很爽。

1
2
3
4
5
6
7
8
9
<resultMap id="EntirBillResultMap" type="Main" autoMapping="true">
<id column="mt_id" property="mtId"/>
<collection property="subs" columnPrefix="s_" ofType="Sub" autoMapping="true">
<id column="mt_id" property="mtId"/>
<collection property="bats" columnPrefix="b_" ofType="Bat" autoMapping="true">
<id column="mt_id" property="mtId"/>
</collection>
</collection>
</resultMap>