博主对SSM的复杂映射关系一直以来都不怎么熟练,所以今天仔细梳理一遍。
resultType和resultMap
用resultType来接收结果的前提是你必须要有一个pojo类。而且pojo中必须包括所有查询出的列名才行。
创建pojo的原则是继承包括查询字段较多的po类。
关于pojo的类别经常使用别名来简化开
<package name="包名"/>
如果进行了上面这样设置,那么所有放在该包下的pojo都可以不用定义了,直接使用类名就可以了
resultMap可以实现延迟加载,resultType无法实现延迟加载。另外牵涉到了association。association用于映射关联查询单个对象的信息
<collection>
是用来处理一对多映射的标签
多对多参照模板,主要是思路要清晰。
<resultMap type="mybatis.po.User" id="UserAndItemsResultMap">
<!-- 用户信息 -->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<!-- 订单信息 -->
<!-- 一个用户对应多个订单,使用collection -->
<collection property="ordersList" ofType="mybatis.po.Orders">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- 订单明细信息 -->
<!-- 一个订单包括多个明细,使用collection -->
<collection property="orderdetails" ofType="mybatis.po.Orderdetail">
<id column="orderdetail_id" property="id"/>
<result column="items_id" property="itemsId"/>
<result column="items_num" property="itemsNum"/>
<result column="orders_id" property="ordersId"/>
<!-- 商品信息 -->
<!-- 一个明细对应一个商品信息,使用association -->
<association property="items" javaType="mybatis.po.Items">
<id column="items_id" property="id"/>
<result column="items_name" property="name"/>
<result column="items_detail" property="detail"/>
<result column="items_price" property="price"/>
</association>
</collection>
</collection>
</resultMap>
总结一点:使用resultMap是针对那些对查询结果映射有特殊要求的功能,,比如特殊要求映射成list中包括多个list。否则使用resultType比较直接。