Mybatis 的输出结果封装

MyBatis的resultType属性用于指定简单查询结果的类型,而resultMap则用于处理复杂的查询结果,如列名与实体属性不一致或一对一、一对多查询。当列名与实体属性不同,可通过resultMap定义列名到属性的映射。此外,resultMap还能实现一对一和一对多查询的封装,提高代码的灵活性和可维护性。
摘要由CSDN通过智能技术生成

resultType 配置结果类型 

resultType 属性可以指定结果集的类型,它支持基本类型实体类类型。它和 parameterType 一样,如果注册过类型别名的,可以直接使用别名。没有注册过的必须 使用全限定类名。当是实体类名称时,还有一个要求,实体类中的属性名称必须查询语句中的列名保持一致否则无法 实现封装。 

例如返回是基本类型:

<select id="findAll" resultType="com.Ycy.domain.User">       
   select * from user 
</select> 

当实体类的属性名称和查询语句中(数据库中列名)相同,这样是可以封装的。

但是当实体类的属性名和查询语句中(数据库中列名)不相同时,就无法封装的,解决方法有两种如下:

第一种:

我们把查询语句的字段名取别名来对应实体类中的属性名   注意:mysql在windows上是不区分大小写的

<select id="findAll" resultType="com.Ycy.domain.User">       
   select id as userId,username as userName,birthday as userBirthday,  sex as userSex,address as userAddress from user 
</select> 

 但是当查询语句别较多时,取别名的方法就显得非常麻烦,修改sql语句比较频繁,这就使用第二种方法比较来得实在。

接下来来了解一下resultMap,第二种方法就是使用resultMap来解决的

resultMap 结果类型 

resultMap的作用:

1、resultMap 标签可以建立查询的列名和实体类的属性名称不一致时建立对应关系。从而实现封装。 在 select 标签中使用 resultMap 属性指定引用即可。

2、resultMap 可以实现将查询结果映射为复杂类 型的 pojo,比如在查询结果映射对象中包括 pojo 和 list 实现一对一查询和一对多查询。 

<select id="findAll" resultMap="userMap">  
    select * from user 
</select> 
<resultMap type="com.Ycy.domain.User" id="userMap">  
    <id column="id" property="userId"/>  
    <result column="username" property="userName"/> 
    <result column="sex" property="userSex"/>  
    <result column="address" property="userAddress"/>  
    <result column="birthday" property="userBirthday"/> 
</resultMap> 

id 标签:用于指定主键字段

result 标签:用于指定非主键字段

column 属性:用于指定数据库列名

property 属性:用于指定实体类属性名称 

实现一对一或者一对多的查询的结果封装

public class student {
    private int id;
    private String name;
    private teacher teachers;
}
<?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="cn.com.Ycy.mybatsi.dao.studentDao">
        <select id="getstudents" resultMap="student_teacher">
            SELECT stu.id,stu.name,teacher.name AS teacher_name,teacher.id AS teacher_id FROM student stu,teacher
            WHERE stu.tid = teacher.id
        </select>
        <resultMap id="student_teacher" type="cn.com.Ycy.mybatsi.domain.student">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <association property="teachers" javaType="cn.com.Ycy.mybatsi.domain.teacher">
                <id column="teacher_id" property="tid"/>
                <result column="teacher_name" property="tname"/>
            </association>
        </resultMap>
</mapper>

具体请参考 Mybatis联合查询详解

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值