MyBatis结果集映射

时间:2022-07-25
本文章向大家介绍MyBatis结果集映射,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

MyBatis配置文件常用配置

1.typeAliases标签,该标签用于配置全局的别名,配置别名后则不再需要写全名,在映射文件中只需要写配置的别名即可,例如:

<configuration>
    <typeAliases>
        <!-- type属性的值为全名,alias的值则为别名 -->
        <typeAlias type="org.zero01.dao.pojo.Student" alias="Student"/>
    </typeAliases>
</configuration>

除了可以配置别名之外,还可以直接配置包扫描,这样映射文件中只需要写相应的类名即可:

<configuration>
    <typeAliases>
        <!-- name属性的值为包名 -->
        <package name="org.zero01.dao.pojo"/>
    </typeAliases>
</configuration>

2.environments标签,该标签用于配置环境,在该标签内可以对事务的管理以及数据库连接池进行配置,例如:

<configuration>
    <typeAliases>
        <!-- name属性的值为包名 -->
        <package name="org.zero01.dao.pojo"/>
    </typeAliases>
    <!-- 配置环境,default为表示默认的 -->
    <environments default="development">

    </environments>
</configuration>

3.environment标签,该标签用于配置具体的环境,可以写多个,例如:

<configuration>
    <typeAliases>
        <!-- name属性的值为包名 -->
        <package name="org.zero01.dao.pojo"/>
    </typeAliases>
    <!-- 配置环境,default为表示默认的 -->
    <environments default="development">
        <!-- 可配置多个数据库环境,id的值为environments标签中default属性的值则表示该数据库为默认的 -->
        <environment id="development">

        </environment>
        <environment id="testDevelopment">

        </environment>
    </environments>
</configuration>

4.transactionManager标签,该标签用于配置事务管理类型,其中的type属性的值为JDBC时代表开启事务,为MANAGED时代表关闭事务,例如:

<configuration>
    <typeAliases>
        <!-- name属性的值为包名 -->
        <package name="org.zero01.dao.pojo"/>
    </typeAliases>
    <!-- 配置环境,default为表示默认的 -->
    <environments default="development">
        <!-- 可配置多个数据库环境,id的值为environments标签中default属性的值则表示该数据库为默认的 -->
        <environment id="development">
            <!-- 事务管理器配置 -->
            <transactionManager type="JDBC"/>
                or
            <transactionManager type="MANAGED"/>
        </environment>
    </environments>
</configuration>

5.dataSource标签,该标签用于配置数据源,以及指定是否使用数据库连接池,例如

<configuration>
    <typeAliases>
        <!-- name属性的值为包名 -->
        <package name="org.zero01.dao.pojo"/>
    </typeAliases>
    <!-- 配置环境,default为表示默认的 -->
    <environments default="development">
        <!-- 可配置多个数据库环境,id的值为environments标签中default属性的值则表示该数据库为默认的 -->
        <environment id="development">
            <!-- 事务管理器配置 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源,POOLED表示使用数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///school"/>
                <property name="username" value="root"/>
                <property name="password" value="your_password"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

6.mappers标签,在该标签内可配置映射文件路径或者映射接口类以及映射文件的url路径,例如:

<configuration>
    <typeAliases>
        <!-- name属性的值为包名 -->
        <package name="org.zero01.dao.pojo"/>
    </typeAliases>
    <!-- 配置环境,default为表示默认的 -->
    <environments default="development">
        <!-- 可配置多个数据库环境,id的值为environments标签中default属性的值则表示该数据库为默认的 -->
        <environment id="development">
            <!-- 事务管理器配置 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源,POOLED表示使用数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///school"/>
                <property name="username" value="root"/>
                <property name="password" value="your_password"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 可配置映射文件路径或者映射接口以及url路径 -->
    <mappers>
        <!-- 配置映射文件的本地路径 -->
        <mapper resource="mapper/StudentMapper.xml"/>
        <!-- 配置映射接口类 -->
        <mapper class="org.zero01.dao.mapperif.StudentMapper"/>
        <!-- 配置映射文件的url路径 -->
        <mapper url="http://url.xxxx.com/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

mappers标签内也可以配置包扫描,与typeAliases标签内的配置方式是一样的:

<mappers>
    <package name="org.zero01.dao.mapperif"/>
</mappers>

注:当接口与XML配置文件混合使用的时候,要注意避免命名空间发生冲突。


MyBatis结果集映射配置

当我们表格的字段名称与字段封装类里的属性名称对应不上的时候,我们就得在配置文件中手动配置结果集对对象属性的映射,不然MyBatis是不会自动映射的,得出来的就会是一个空对象。

例如,我现在有一张student表,表格结构如下:

然后编写了一个表格的字段封装类,代码如下:

package org.zero01.dao.pojo;

public class Student {

    private int id;
    private String name;
    private int stuAge;
    private String stuSex;
    private String stuAddress;
    ... getter setter 略 ...
}

接口类代码如下:

package org.zero01.dao.mapperif;

import org.zero01.dao.pojo.Student;

public interface StudentMapper {
    public Student selectById(int id);
}

可以看到对象属性名称与表格字段名称不一致,这时候就需要配置结果集的映射器,在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="org.zero01.dao.mapperif.StudentMapper">
    <resultMap id="stuMap" type="Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="stuAge" column="age"/>
        <result property="stuSex" column="sex"/>
        <result property="stuAddress" column="address"/>
    </resultMap>
    <select id="selectById" resultMap="stuMap" parameterType="int">
        select * from student where sid=#{0}
    </select>
</mapper>

编写一个简单的测试用例进行测试,测试代码如下:

package org.zero01.test;

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 org.json.JSONObject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zero01.dao.mapperif.StudentMapper;
import org.zero01.dao.pojo.Student;

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

public class TestMybatis {

    private SqlSession sqlSession;
    private StudentMapper studentMapper;

    @Before
    public void startTest() throws IOException {
        String confPath = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(confPath);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        studentMapper = sqlSession.getMapper(StudentMapper.class);
    }

    @Test
    public void testSelectById() {
        Student student = studentMapper.selectById(24);
        Assert.assertNotNull(student);
        System.out.println(new JSONObject(student));
    }

    @After
    public void endTest() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

控制台打印结果如下,没有问题:

{"stuSex":"女","name":"Milen","stuAddress":"深圳","id":24,"stuAge":20}

如果我们需要进行连接查询的时候,也需要用到结果集映射,例如我现在要查询student表与studentlog中sid一致的记录。studentlog表格结构如下:

同样的,需要先创建一个表格字段封装类:

package org.zero01.dao.pojo;

import java.util.Date;

public class StudentLog {

    private int log_id;
    private int id;
    private String name;
    private int stuAge;
    private String stuSex;
    private String stuAddress;
    private String operation_type;
    private Date log_time;
    ... getter setter 略 ...
}

然后在Student类中,增加StudentLog属性:

package org.zero01.dao.pojo;

public class Student {

    private int id;
    private String name;
    private int stuAge;
    private String stuSex;
    private String stuAddress;
    private StudentLog studentLog;
    ... getter setter 略 ...
}

然后需要在XML文件中使用association标签来配置连接查询的结果集映射,如下示例:

<?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="org.zero01.dao.mapperif.StudentMapper">
    <resultMap id="stuMap" type="Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="stuAge" column="age"/>
        <result property="stuSex" column="sex"/>
        <result property="stuAddress" column="address"/>
        <association property="studentLog" javaType="StudentLog" fetchType="lazy">
            <id property="log_id" column="log_id"/>
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="stuAge" column="age"/>
            <result property="stuSex" column="sex"/>
            <result property="stuAddress" column="address"/>
            <result property="operation_type" column="operation_type"/>
            <result property="log_time" column="log_time"/>
        </association>
    </resultMap>
    <select id="selectInnerLog" resultMap="stuMap">
        select * from student stu inner join studentlog stulog on  stu.`sid`=stulog.`sid`
    </select>
</mapper>

其中javaType属性用于指定将结果集数据封装成哪种Java类型,在这里为自定义类型,而fetchType属性指定是否开启延迟加载,lazy为开启,eager为禁止。也可以在mybatis配置文件中通过settings标签来配置开启或关闭延迟加载,这种配置方式是全局生效的,如下示例:

<configuration>
    ...
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
    ...
</configuration>

association标签中有一个select属性,通过该属性我们可以执行指定的查询语句。例如我现在需要查询一个学生的记录,我希望查询的时候能统计出表格中与该学生同名的学生数量。在Studnet中加多一个count属性:

package org.zero01.dao.pojo;

public class Student {

    private int id;
    private String name;
    private int stuAge;
    private String stuSex;
    private String stuAddress;
    private StudentLog studentLog;
    private int count;
    ... getter setter 略 ...
}

然后编辑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="org.zero01.dao.mapperif.StudentMapper">
    <resultMap id="stuMap" type="Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="stuAge" column="age"/>
        <result property="stuSex" column="sex"/>
        <result property="stuAddress" column="address"/>
        <association property="count" column="sname" select="countStu"/>
    </resultMap>
    <select id="selectById" resultMap="stuMap" parameterType="int">
        select * from student where sid=#{0}
    </select>
    <select id="countStu" resultType="int">
        select count(*) as total from student where sname=#{0}
    </select>
</mapper>

注:查询语句不能是无参数值的,因为使用select属性时必须要有column属性,这时候的column属性是用来传递参数的。例如:select count(*) as total from student这类语句是无效的。而如果要传递多个参数时,需要使用大括号括起来,例如:column="{prop1=sid,prop2=sname,prop3=age,}"

从以上简单的示例中,可以看到association标签完成的是一对一的级联操作的结果集映射,如果是一对多的操作时就需要使用collection标签进行结果集的映射。例如,我在Student里增加一个studentLogs属性,要求把查询出来的StudentLog对象都放在这个集合里,这种操作就是一对多:

package org.zero01.dao.pojo;

public class Student {

    private int id;
    private String name;
    private int stuAge;
    private String stuSex;
    private String stuAddress;
    private StudentLog studentLog;
    private int count;
    private List<StudentLog> studentLogs;
    ... getter setter 略 ...
}

编辑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="org.zero01.dao.mapperif.StudentMapper">
    <resultMap id="stuMap" type="Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="stuAge" column="age"/>
        <result property="stuSex" column="sex"/>
        <result property="stuAddress" column="address"/>
        <!-- ofType属性用于指定将数据封装成哪个对象 -->
        <collection property="studentLogs" javaType="List" ofType="StudentLog">
            <id property="log_id" column="log_id"/>
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="stuAge" column="age"/>
            <result property="stuSex" column="sex"/>
            <result property="stuAddress" column="address"/>
            <result property="operation_type" column="operation_type"/>
            <result property="log_time" column="log_time"/>
        </collection>
    </resultMap>
    <select id="selectInnerLog" resultMap="stuMap">
        SELECT * FROM student stu INNER JOIN studentlog stulog ON stu.`sid`=stulog.`sid`
    </select>
</mapper>