5.resultType和resultMap

zhanglei 2022年06月02日 422次浏览

resultType:作为select标签里的属性,表示mybatis执行sql后得到的java对象类型。规则:同名列赋值给同名属性。

​ 返回类型为Map集合时,结果只能是一行,否则报错

resultMap:结果映射,设置传值关系,用于列名和属性名不同的情况。(用法见StudentDao.xml)

resultMap 和 resultType只能二选一,不能同时使用。

mybais-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--配置数据源:创建Connection对象-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定其他mapper文件的位置
    找到其他mapper文件的目的是找到sql语句

    使用注意:
        resource="mapper.文件的路径,用/分割"-->

    <mappers>
        <mapper resource="Dao/StudentDao.xml"/>
    </mappers>
</configuration>

StudentDao接口

package Dao;

import domain.Student;
import domain.Teacher;

import java.util.HashMap;

public interface StudentDao {

    Student selectById(Integer i);

    //测试resultType的规则:赋值给与列名相同名称的属性
    //TeacherDemo里只有email和age与表中的列名相同
    Teacher selectById2(Integer i);

    //当resultType的值为Map时
    HashMap<Object,Object> selectMap(Integer i);

    //测试resultMap:建立映射关系,使得id列的值夫给属性tid,name列的值赋给属性tname
    Teacher selectById3(Integer i);
    //处理列名和属性名不同的情况处理用resultMap建立关系外,还可以用resultType
    Teacher selectById4(Integer i);
}

StudentDao.xml文件

<?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="Dao.StudentDao">

    <!--
        resultType:表示mybatis执行sql后得到的java对象类型
                   规则:同名列赋值给同名属性
    -->


    <select id="selectById" resultType="domain.Student">
        select id,name,email,age from student where id=#{id}
    </select>

    <select id="selectById2" resultType="domain.Teacher">
        select id,name,email,age from student where id=#{id}
    </select>

    <!--返回类型为Map时,结构只能是一行,否则报错-->
    <select id="selectMap" resultType="java.util.HashMap">
        select id,name,age from student where id=#{id}
    </select>

    <!--设置结果传值关系 id:给映射关系起名称 type:被赋值的java类型的全限定名称-->
    <resultMap id="resultmap" type="domain.Teacher">
        <!--主键属性-->
        <result column="id" property="tid"/>
        <!--其他属性-->
        <result column="name" property="tname"/>
    </resultMap>

    <!--第二个参数表明按照名为resultmap的映射关系给Teacher的属性赋值
     在select标签下,resultType和resultMap不能同时用,二选一
     -->
    <select id="selectById3" resultMap="resultmap">
        select id,name,email,age from student where id=#{id}
    </select>

    <!--设置id和name的属性别名,也可以对应-->
    <select id="selectById4" resultType="domain.Teacher">
        select id as tid,name as tname,email,age from student where id=#{id}
    </select>
</mapper>

实体类1Student

package domain;

public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "学生实体{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

实体类2Teacher

package domain;
//作为接受查询结果的对象
public class Teacher {
    private Integer tid;
    private String tname;
    private String email;
    private Integer age;

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "教师实体{" +
                "tid=" + tid +
                ", tname='" + tname + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

工具类MyBatisUtil

package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    //获得SqlSessionFactory
    public static SqlSessionFactory sqlSessionFactory;
    static{
        String config="mybatis-config.xml ";
        try {
            InputStream inputStream = Resources.getResourceAsStream(config);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //获得sqlSession
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

resultType的测试类

import Dao.StudentDao;
import domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import domain.Teacher;
import util.MyBatisUtil;

import java.util.HashMap;
//resultType和resultMap(结果映射:用于列名和属性名不一样的情况)
public class MyTest {
    //resultType为Student
    @Test
    public void testSelectById(){
        //获取sqlSession
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao实现类
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用接口中的方法
        Student student = mapper.selectById(1);
        System.out.println(student);
        sqlSession.close();
    }

    //resultType为Teacher!!!
    //最后只有email和age被赋值了
    @Test
    public void testSelectById2(){
        //获取sqlSession
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao实现类
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用接口中的方法
        Teacher teacher = mapper.selectById2(1);
        System.out.println(teacher);
        sqlSession.close();
    }

    //resultType为map---查询结果只能是一行数据
    @Test
    public void testSelectMap(){
        //获取sqlSession
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao实现类
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用接口中的方法
        HashMap<Object,Object> hm = mapper.selectMap(1);
        System.out.println(hm);
        sqlSession.close();
    }
    //resultType规则:列名和属性名相同才会传值
  
}

resultType测试结果

//testSelectById
学生实体{id=1, name='张磊', email='zl@163.com', age=23}

//testSelectById2
教师实体{tid=null, tname='null', email='zl@163.com', age=23}

//testSelectMap
{name=张磊, id=1, age=23}

resultMap测试类

import Dao.StudentDao;
import domain.Teacher;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import util.MyBatisUtil;
//resultMap:结果映射,可以自定义列名和java对象的属性的对应关系
//常用在列名和属性名不同的前提下
//用法:先定义resultMap标签,指定列名和属性名称的关系
public class MyTest_resultMap {
    @Test
    public void testresultMap1(){
        //获取Sqlsession对象
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao的实现类的对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用方法
        Teacher teacher = mapper.selectById3(1);
        System.out.println(teacher);
        sqlSession.close();
    }
    //也可用别名解决列名和属性名不同的情况(不常用)
    @Test
    public void testresultMap2(){
        //获取Sqlsession对象
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao的实现类的对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用方法
        Teacher teacher = mapper.selectById4(1);
        System.out.println(teacher);
        sqlSession.close();
    }
}

resultMap测试结果

//testresultMap1
教师实体{tid=1, tname='张磊', email='zl@163.com', age=23}

//testresultMap2
教师实体{tid=1, tname='张磊', email='zl@163.com', age=23}