mybatis复杂映射
一、一对一
<mapper namespace="com.example.demo.mapper.OrderMapper">
<resultMap id="orderMap" type="com.example.demo.pojo.Order">
<result property="id" column="id"></result>
<result property="orderTime" column="orderTime"></result>
<result property="total" column="total"></result>
<association property="user" javaType="com.example.demo.pojo.User">
<result property="id" column="uid"></result>
<result property="username" column="username"></result>
</association>
</resultMap>
<!--resultMap:手动来配置实体属性与表字段的映射关系-->
<select id="findAll" resultMap="orderMap">
select *
from orders o,
user u
where o.uid = u.id
</select>
</mapper>
二、一对多
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="userMap" type="com.example.demo.pojo.User">
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<result property="password" column="password"></result>
<result property="birthday" column="birthday"></result>
<collection property="orderList" ofType="com.example.demo.pojo.Order">
<result property="id" column="oid"></result>
<result property="orderTime" column="orderTime"></result>
<result property="total" column="total"></result>
</collection>
</resultMap>
<!--resultMap:手动来配置实体属性与表字段的映射关系-->
<select id="findAll" resultMap="userMap">
select *, o.id oid
from user u
left join orders o on u.id = o.uid
</select>
</mapper>
延迟加载: fetchType=“lazy”,assoication、collection可配置该属性,当使用到子属性时才去查询
也可全局配置:
xml <settings> <!--开启全局延迟加载功能--> <setting name="lazyLoadingEnabled" value="true"/> </settings>
三、多对多
同一对多
示例代码见:https://gitee.com/ixinglan/mybatis-tec.git