MyBatis联表查询,对多的关系
不论是一对多还是多对多的联表查询,都可以在主表的pojo类中设置集合属性,结合Maybatis的resultMap标签中的子标签collection,封装附表的结果集。
<resultMap id="BaseResultMap" type="org.example.pojo.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="birthday" jdbcType="DATE" property="birthday" />
<result column="gender" jdbcType="VARCHAR" property="gender" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="remark" jdbcType="VARCHAR" property="remark" />
<result column="station" jdbcType="VARCHAR" property="station" />
<result column="telephone" jdbcType="VARCHAR" property="telephone" />
</resultMap>
<resultMap id="userWithMultiTableMap" type="org.example.pojo.User" extends="BaseResultMap">
<collection property="roles" ofType="org.example.pojo.Role">
<collection property="permissions" ofType="org.example.pojo.Permission">
<result column="keyword" property="keyword"/>
</collection>
</collection>
</resultMap>
当定义有集合的结果映射集使用extend属性时,将会报以下异常。
但在resultMap中使用collection子标签的本意就是让附表的多个结果集放在主表的一个集合属性中,这样的异常意味着还要让主表的pojo类更为集合的方式接收数据,如此并未达到使用该标签的本意,所以不用extend属性时,附表的结果集将会正常进行映射。
<!--更改结果集映射,需要映射的数据,自己添加上-->
<resultMap id="userWithMultiTableMap" type="org.example.pojo.User">
<result column="username" property="username"/>
<result column="password" property="password"/>
<collection property="roles" ofType="org.example.pojo.Role">
<collection property="permissions" ofType="org.example.pojo.Permission">
<result column="keyword" property="keyword"/>
</collection>
</collection>
</resultMap>
最后,需要联表查询的情况,采用分步查询时,可以使用resultMap的extends的属性,完成上面所要达到的操作。