目录
1.一对一查询
1.1一对一查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户,一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.caoyan.mapper.OrderMapper">
<resultMap id="orderMap" type="order">
<!-- 手动指定字段与实体属性的映射关系
column:数据表的字段名称
property:实体的属性名称
-->
<id column="oid" property="id"/>
<result column="ordertime" property="ordertime"/>
<result column="total" property="total"/>
<!-- <result column="uid" property="user.id"/>
<result column="username" property="user.username"/>
<result column="password" property="user.password"/>
<result column="birthday" property="user.birthday"/> -->
<!--
property:当前实体(order)中的属性名称(private User user)
javaType:当前实体(order)中的属性的类型(User)
-->
<association property="user" javaType="user">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="birthday" property="birthday"/>
</association>
</resultMap>
<select id="findAll" resultMap="orderMap">
select *,o.id oid from orders o,user u where o.uid=u.id
</select>
</mapper>
2.一对多查询
2.1一对多查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户,一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.caoyan.mapper.UserMapper">
<resultMap id="userMap" type="user">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="birthday" property="birthday"/>
<!-- 配置集合信息
property:集合名称
ofType:当前集合中的数据类型
-->
<collection property="orderList" ofType="order">
<!-- 封装order的数据 -->
<id column="oid" property="id"/>
<result column="ordertime" property="ordertime"/>
<result column="total" property="total"/>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
SELECT *,o.id oid FROM user u,orders o where u.id=o.uid
</select>
</mapper>
3.多对多查询
3.1多对多查询的模型
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用,多对多查询的需求:查询用户同时查询出该用户的所有角色。
<resultMap id="userRoleMap" type="user">
<!-- user的信息 -->
<id column="userId" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="birthday" property="birthday"/>
<!-- user内部的roleList信息 -->
<collection property="roleList" ofType="role">
<id column="roleId" property="id"/>
<result column="roleName" property="roleName"/>
<result column="roleDesc" property="roleDesc"/>
</collection>
</resultMap>
<select id="findUserAndRoleAll" resultMap="userRoleMap">
SELECT * FROM user u,sys_user_role ur,sys_role r where u.id=ur.userId AND ur.roleId=r.id
</select>
4.知识小结
MyBatis多表配置方式:
- 一对一配置:使用<resultMap>+<association>做配置
- 一对多配置:使用<resultMap>+<collection>做配置
- 多对多配置:使用<resultMap>+<collection>做配置