mybatis多表操作 ResultMap

MyBatis的多表操作 – ResultMap封装结果集

1. 一对一查询

1.1一对一查询的模型

用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
在这里插入图片描述

1.2 创建Order和User实体
public class Order {
    private int id;
    private Date ordertime;
    private double total;
    
    //代表当前订单从属于哪一个客户
    private User user;
}
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
}
1.3 创建 OrderMapper 接口
public interface OrderMapper {
	List<Order> findAll();
}
1.4 配置OrderMapper.xml
<mapper namespace="com.itheima.mapper.OrderMapper">
    # 设置封装对象的结果集
    <resultMap id="orderMap" type="com.itheima.domain.Order">
        <result column="uid" property="user.id"></result>
        <result column="username" property="user.username"></result>
        <result column="password" property="user.password"></result>
        <result column="birthday" property="user.birthday"></result>
    </resultMap>
    
    <select id="findAll" resultMap="orderMap">
        select * from orders o,user u where o.uid=u.id
    </select>
</mapper>

还可以这样配置

<resultMap id="orderMap" type="com.itheima.domain.Order">
    <result property="id" column="id"></result>
    <result property="ordertime" column="ordertime"></result>
    <result property="total" column="total"></result>
    <association property="user" javaType="com.itheima.domain.User">
        <result column="uid" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
    </association>
</resultMap>
1.5 测试结果
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<Order> all = mapper.findAll();
for(Order order : all){
	System.out.println(order);
}

在这里插入图片描述

2. 一对多查询

2.1 一对多查询的模型

用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
在这里插入图片描述

2.2 修改User实体
public class Order {
    private int id;
    private Date ordertime;
    private double total;
    
    //代表当前订单从属于哪一个客户
    private User user;
}
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    
    //代表当前用户具备哪些订单
    private List<Order> orderList;
}
public interface UserMapper {
	List<User> findAll();
}
2.3 创建UserMapper接口
public interface UserMapper {
	List<User> findAll();
}
2.4 UserMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
    <resultMap id="userMap" type="com.itheima.domain.User">
        <result column="id" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <collection property="orderList" ofType="com.itheima.domain.Order">
            <result column="oid" property="id"></result>
            <result column="ordertime" property="ordertime"></result>
            <result column="total" property="total"></result>
        </collection>
    </resultMap>
    
    <select id="findAll" resultMap="userMap">
        select *,o.id oid from user u left join orders o on u.id=o.uid
    </select>
</mapper>
2.5 测试结果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
for(User user : all){
    System.out.println(user.getUsername());
    List<Order> orderList = user.getOrderList();
    for(Order order : orderList){
        System.out.println(order);
    }
    System.out.println("----------------------------------");
}

在这里插入图片描述

3. 多对多查询

3.1 多对多查询的模型

用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
在这里插入图片描述

3.2 创建Role实体,修改User实体
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    
    //代表当前用户具备哪些订单
    private List<Order> orderList;
    //代表当前用户具备哪些角色
    private List<Role> roleList;
}
public class Role {
    private int id;
    private String rolename;
}
3.3 创建UserMapper接口
List<User> findAllUserAndRole();
3.4 UserMapper.xml
<resultMap id="userRoleMap" type="com.itheima.domain.User">
    <result column="id" property="id"></result>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
    <collection property="roleList" ofType="com.itheima.domain.Role">
        <result column="rid" property="id"></result>
        <result column="rolename" property="rolename"></result>
    </collection>
</resultMap>

<select id="findAllUserAndRole" resultMap="userRoleMap">
    select u.*,r.*,r.id rid from user u left join user_role ur on 
    u.id=ur.user_id
    inner join role r on ur.role_id=r.id
</select>
3.5 测试结果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAllUserAndRole();
for(User user : all){
    System.out.println(user.getUsername());
    List<Role> roleList = user.getRoleList();
    for(Role role : roleList){
        System.out.println(role);
    }
    System.out.println("----------------------------------");
}

在这里插入图片描述

4. MyBatis多表配置方式:

一对一配置:使用做配置
一对多配置:使用+做配置
多对多配置:使用+做配置

5. association 和 collection区别

1、关联-association 集合-collection
2、所以association是用于一对一和多对一,而collection是用于一对多的关系
3、JavaType和ofType都是用来指定对象类型的
JavaType是用来指定pojo中属性的类型
ofType指定的是映射到list集合属性中pojo的类型

6. resultMap的基础知识

<!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<resultMap id="唯一的标识" type="映射的pojo对象">
  <id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
  <result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
    
  <association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
    <id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
    <result  column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
  </association>
    
  <!-- 集合中的property须为oftype定义的pojo对象的属性-->
  <collection property="pojo的集合属性" ofType="集合中的pojo对象">
    <id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
    <result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />  
  </collection>
    
</resultMap>

 <collection column="传递给嵌套查询语句的字段参数" property="pojo对象中集合属性" ofType="集合属性中的pojo对象" select="嵌套的查询语句" > 
 </collection>

7. association

嵌套结果集
<!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则  -->
	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联集合类型的属性的封装规则 
			ofType:指定集合里面元素的类型
		-->
		<collection property="emps" ofType="com.atguigu.mybatis.bean.Employee">
			<!-- 定义这个集合中元素的封装规则 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>
	<!-- public Department getDeptByIdPlus(Integer id); -->
	<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.last_name last_name,e.email email,e.gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e
		ON d.id=e.d_id
		WHERE d.id=#{id}
	</select>
association-分段查询
<!-- collection:分段查询 -->
	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="com.atguigu.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>

	<!-- public Department getDeptByIdStep(Integer id); -->
	<select id="getDeptByIdStep" resultMap="MyDeptStep">
		select id,dept_name from tbl_dept where id=#{id}
	</select>
	
	<!-- 扩展:多列的值传递过去:
			将多列的值封装map传递;
			column="{key1=column1,key2=column2}"
		fetchType="lazy":表示使用延迟加载;
				- lazy:延迟
				- eager:立即
	 -->

8.association-分段查询&延迟加载

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="jdbcTypeForNull" value="NULL"/>

    <!--显式的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题  -->
    <setting name="cacheEnabled" value="true"/>
    <!-- 延迟加载 --->
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

延迟加载:就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载.

好处:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。

<!--显式的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题  -->
<setting name="cacheEnabled" value="true"/>
<!-- 延迟加载 --->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
```

延迟加载:就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载.

好处:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。

坏处:因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus 是一个 MyBatis 的增强工具,它提供了一系列增强功能来简化 MyBatis 的使用。其中之一就是提供了一个比 MyBatis 更加方便的结果映射方式,就是通过 `ResultMap`。 `ResultMap` 是 MyBatis 提供的结果映射器,它可以将数据库查询返回的结果映射成 Java 对象。MyBatis-Plus 的 `ResultMap` 功能就是在 MyBatis 的 `ResultMap` 基础上进行的增强。 在 MyBatis-Plus 中,我们可以通过 `@TableName` 注解来指定实体类和数据库表的映射关系,然后使用 `@TableField` 注解来指定实体类中的属性和数据库表中的字段的映射关系。 使用 MyBatis-Plus 的 `ResultMap` 功能时,我们只需要在实体类中定义一个 `ResultMap`,然后在查询语句中使用该 `ResultMap` 即可将查询结果映射成 Java 对象。 以下是一个使用 MyBatis-Plus `ResultMap` 的示例: ```java @TableName("user") public class User { @TableId(value = "id", type = IdType.AUTO) private Long id; @TableField("username") private String username; @TableField("password") private String password; // getter 和 setter 省略 } // 定义 ResultMap private static final ResultMap USER_RESULT_MAP = new ResultMap.Builder(configuration, "userResultMap", User.class, new ArrayList<ResultMapping>()) .id(new ResultMapping.Builder(configuration, "id", "id", Long.class).build()) .result(new ResultMapping.Builder(configuration, "username", "username", String.class).build()) .result(new ResultMapping.Builder(configuration, "password", "password", String.class).build()) .build(); // 使用 ResultMap 查询 List<User> userList = sqlSession.selectList("com.example.mapper.UserMapper.selectUserList", null, new RowBounds(0, 10), USER_RESULT_MAP); ``` 在上面的示例中,我们首先使用 `@TableName` 和 `@TableField` 注解指定了实体类和数据库表之间的映射关系。然后我们定义了一个 `ResultMap`,并在其中指定了实体类中的属性和数据库表中的字段的映射关系。最后我们在查询语句中使用该 `ResultMap` 将查询结果映射成 Java 对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值