一文搞定Mybatis 一对多延迟加载,并且子查询中与主表字段不对应

Posted Java架构-大仙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一文搞定Mybatis 一对多延迟加载,并且子查询中与主表字段不对应相关的知识,希望对你有一定的参考价值。

Mybatis 一对多延迟加载,并且子查询中与主表字段不对应应用说明。

实现一对多关联(懒加载),一个教研组对应多个教师,既:教师的教研编号与教研组的教研编号关联,并且教师关联教研组外键与教研组编号不一致。

1、工程资源配置文件

1)、本应用实际应用到了(开启延迟加载配置、关闭立即加载配置);

2) 、外关联查询语句对应xml文件 :

3)、主查询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>

    <settings>
        <!-- 开启日志,并制定使用的具体日志,LOG4J 对应 log4j.properties的文件名 -->
        <setting name="logImpl" value="LOG4J"/>
        <!-- 开启延迟加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- g关闭立即加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <!-- 转换器 -->
    <typeHandlers>
        <!-- 把java类的boolean类型转换数据 int,数据库int转换为java类的boolean类型 -->
        <typeHandler handler="com.mybatis03.util.BooleanAndIntConverter" javaType="Boolean" jdbcType="INTEGER"/>
    </typeHandlers>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis01"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 加载映射文件 -->
        <mapper resource="com/mybatis03/mapper/personMapper.xml"/>
        <mapper resource="com/mybatis03/mapper/TeacherMapper.xml"/>
        <mapper resource="com/mybatis03/mapper/teacherCourseMapper.xml"/>
        <!-- 外关联查询语句对应xml文件 -->
        <mapper resource="com/mybatis03/mapper/teacherGroupToTeacherMapper.xml"/>
    </mappers>
</configuration>

2、mapper文件

2.1 教师.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="com.mybatis03.mapper.TeacherMapper">
    <!-- 实现一对多关联(懒加载),一个教研组对应多个教师,既:教师的教研编号与教研组的教研编号关联  -->
    <select id="queryWithLazyGroupAndTeachers"  parameterType="int" resultMap="lazyGroupTeacherMap">
        SELECT g.*,g.groupID AS groupno FROM teachergroup g
        WHERE g.groupid =#groupid
    </select>
    <!--类和表对应关系 (一对多都用collection,一对一用 association) -->
    <resultMap id="lazyGroupTeacherMap" type="com.mybatis03.bean.TeacherGroup">
        <!-- 因为type主类是TeacherGroup,所以先配置 TeacherGroup类属性对应关系 -->
        <id property="groupID" column="groupid" />
        <result property="groupName" column="groupname"/>
        <!-- 配置成员属性教师 ,一对多;属性类型:javaType,属性元素类型 ofType-->
        <!--property 中的属性为实体类中的属性,column对应数据库中的字段 -->
        <collection property="teacherList" ofType="com.mybatis03.bean.Teacher"
         select="com.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO" column="groupno" >
        </collection>
    </resultMap>
</mapper>

说明:由于在关联过程中,教研组编号与教师编号不一致,通过重命名方式使。关联字段一致:

A、本应用实现懒加载使用原始SQL关联查询应为:SELECT g.,t. FROM teachergroup g INNER JOIN teacher t ON g.groupid = t.groupno WHERE g.groupid =#groupid

B、应用懒加载实现说明解决字段不一致参加红色浪线;


2.2 外关联查询教师信息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="com.mybatis03.mapper.teacherGroupToTeacherMapper">
    <!-- 查询教师,延迟加载应用此配置文件 -->
    <!-- 查询教师对应的课程 -->
    <select id="queryGroupToTeacherByNO" parameterType="int" resultType="com.mybatis03.bean.Teacher">
        SELECT * FROM teacher WHERE groupno = #groupno
    </select>
</mapper>


3、教师接口类

public interface TeacherMapper 
    /* 实现一对多关联(延迟加载),一个教研组对应多个教师,既:教师的教研编号与教研组的教研编号关联  */
    TeacherGroup queryWithLazyGroupAndTeachers(int groupNo);

4、实体类

4.1 教师实体类

public class Teacher 
    @Override
    public String toString() 
        return "Teacher" +
                "teaNo=" + teaNo +
                ", courseNo=" + courseNo +
                ", teaName='" + teaName + '\\'' +
                ", teacherCourse" +

                "courseNo=" + teacherCourse.getCourseNo() +
                ", courseName=" + teacherCourse.getCourseName() +""+

                '';
    


    /* 教师编号 */
    private int teaNo;
    /* 课程编号 */
    private int courseNo;
    /* 教师名称 */
    private String teaName;

    /* 教师课程类,课程作为老师属性 */
    private TeacherCourse teacherCourse;

    /* 新增一个教研组编号,用于关联教研组编号,实现多对一关联*/
    private int  groupNo;

    /**
     *  <!--利用resultMap实现一对一 -->
     * @return
     */
    public TeacherCourse getTeacherCourse() 
        return teacherCourse;
    

    public void setTeacherCourse(TeacherCourse teacherCourse) 
        this.teacherCourse = teacherCourse;
    

    public int getGroupNo() 
        return groupNo;
    

    public void setGroupNo(int groupNo) 
        this.groupNo = groupNo;
    

    public int getCourseNo() 
        return courseNo;
    

    public void setCourseNo(int courseNo) 
        this.courseNo = courseNo;
    

    public int getTeaNo() 
        return teaNo;
    

    public void setTeaNo(int teaNo) 
        this.teaNo = teaNo;
    

    public String getTeaName() 
        return teaName;
    

    public void setTeaName(String teaName) 
        this.teaName = teaName;
    

4.2 教研组实体类

public class TeacherGroup 
    @Override
    public String toString() 

        String str = "";
        for (int i = 0; i < teacherList.size(); i++) 

            str += "teaNo=" + teacherList.get(i).getTeaNo() + ",";
            str += "courseNo=" + teacherList.get(i).getCourseNo() + ",";
            str += "teaName=" + teacherList.get(i).getTeaName() + ",";
            str += "groupNo=" + teacherList.get(i).getGroupNo();
            if (i < teacherList.size() - 1) 
                str += ",";
            

        
        return "TeacherGroup" +
                "groupID=" + groupID +
                ", groupName='" + groupName + '\\'' +
                ", teacherList" +
//                "teaNo=" + teacherList.get(0).getTeaNo() + "," +
//                "courseNo=" + teacherList.get(0).getCourseNo() + "," +
//                "teaName=" + teacherList.get(0).getTeaName() + "," +
//                "groupNo=" + teacherList.get(0).getGroupNo() + "," +
                    str+
                "" +
                '';
    


    /* 教研组编号:汉语教研组 1,英语教研组2,日语教研组3,德语教研组 4 */
    /* 教研组编号,用于关联教师编号,实现多对一关联*/
    private int groupID;

    /* 教研组名称,英语教研组,日语教研组还是德语教研组*/
    private String groupName;

    /* 一个教研组对应多个教师,属于一对多关系。关联关系:教师的教研编号与教研组的教研编号关联 */
    private List<Teacher> teacherList;

    public List<Teacher> getTeacherList() 
        return teacherList;
    

    public void setTeacherList(List<Teacher> teacherList) 
        this.teacherList = teacherList;
    

    public int getGroupID() 
        return groupID;
    

    public void setGroupID(int groupID) 
        this.groupID = groupID;
    

    public String getGroupName() 
        return groupName;
    

    public void setGroupName(String groupName) 
        this.groupName = groupName;
    

5、测试类

@Test
    public void queryWithLazyGroupAndTeachers() throws Exception 
        Reader reader = Resources.getResourceAsReader("mybatis-03.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

        SqlSession session = sessionFactory.openSession();
        int groupNo = 1;
        TeacherMapper personMapper = session.getMapper(TeacherMapper.class);
        TeacherGroup teacherGroup = personMapper.queryWithLazyGroupAndTeachers(groupNo);
        System.out.println("教研组编号:"+teacherGroup.getGroupID()+",教研组名称:"+teacherGroup.getGroupName());
        List<Teacher> teacherList = teacherGroup.getTeacherList();
        for (Teacher teacher : teacherList) 
            System.out.println("教师编号:"+teacher.getTeaNo()+",教师名称:"
                    +teacher.getTeaName()+",教研组编号:"+teacher.getGroupNo());
        
    

测试结果

"C:\\Program Files\\Java\\jdk1.8.0_25\\bin\\java" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\\Users\\newsoft\\AppData\\Roaming\\JetBrains\\IntelliJ IDEA 2017.3.5\\lib\\idea_rt.jar=1031:C:\\Users\\newsoft\\AppData\\Roaming\\JetBrains\\IntelliJ IDEA 2017.3.5\\bin" -Dfile.encoding=UTF-8 -classpath "C:\\Users\\newsoft\\AppData\\Roaming\\JetBrains\\IntelliJ IDEA 2017.3.5\\lib\\idea_rt.jar;C:\\Users\\newsoft\\AppData\\Roaming\\JetBrains\\IntelliJ IDEA 2017.3.5\\plugins\\junit\\lib\\junit-rt.jar;C:\\Users\\newsoft\\AppData\\Roaming\\JetBrains\\IntelliJ IDEA 2017.3.5\\plugins\\junit\\lib\\junit5-rt.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\junit\\platform\\junit-platform-launcher\\1.5.2\\junit-platform-launcher-1.5.2.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\apiguardian\\apiguardian-api\\1.1.0\\apiguardian-api-1.1.0.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\junit\\platform\\junit-platform-engine\\1.5.2\\junit-platform-engine-1.5.2.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\opentest4j\\opentest4j\\1.2.0\\opentest4j-1.2.0.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\junit\\platform\\junit-platform-commons\\1.5.2\\junit-platform-commons-1.5.2.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\junit\\jupiter\\junit-jupiter-engine\\5.5.2\\junit-jupiter-engine-5.5.2.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\junit\\jupiter\\junit-jupiter-api\\5.5.2\\junit-jupiter-api-5.5.2.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\junit\\vintage\\junit-vintage-engine\\5.5.2\\junit-vintage-engine-5.5.2.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\junit\\junit\\4.12\\junit-4.12.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\hamcrest\\hamcrest-core\\1.3\\hamcrest-core-1.3.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\charsets.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\deploy.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\access-bridge-64.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\cldrdata.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\dnsns.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\jaccess.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\jfxrt.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\localedata.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\nashorn.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\sunec.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\sunjce_provider.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\sunmscapi.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\sunpkcs11.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\ext\\zipfs.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\javaws.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\jce.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\jfr.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\jfxswt.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\jsse.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\management-agent.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\plugin.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\resources.jar;C:\\Program Files\\Java\\jdk1.8.0_25\\jre\\lib\\rt.jar;D:\\ideaworkspace\\ProjectStudy\\mybatis-02\\target\\classes;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\hamcrest\\hamcrest-core\\2.1\\hamcrest-core-2.1.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\hamcrest\\hamcrest\\2.1\\hamcrest-2.1.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\mybatis\\mybatis\\3.4.5\\mybatis-3.4.5.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\log4j\\log4j\\1.2.17\\log4j-1.2.17.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\slf4j\\slf4j-log4j12\\1.7.12\\slf4j-log4j12-1.7.12.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\slf4j\\slf4j-api\\1.7.30\\slf4j-api-1.7.30.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\cglib\\cglib\\3.3.0\\cglib-3.3.0.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\org\\ow2\\asm\\asm\\7.1\\asm-7.1.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\net\\logstash\\logback\\logstash-logback-encoder\\5.3\\logstash-logback-encoder-5.3.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\com\\fasterxml\\jackson\\core\\jackson-databind\\2.10.3\\jackson-databind-2.10.3.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\com\\fasterxml\\jackson\\core\\jackson-annotations\\2.10.3\\jackson-annotations-2.10.3.jar;D:\\download\\lib\\mavenTollTransfer\\mic-repository\\com\\fasterxml\\jackson\\core\\jackson-core\\2.10.3\\jackson-core-2.10.3.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit5 com.mybatis03.test.testTeacher01,queryWithLazyGroupAndTeachers
[lsjSso]2021-10-20 09:17:47,649-org.apache.ibatis.logging.LogFactory-0   [main]DEBUGorg.apache.ibatis.logging.LogFactory-Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
[lsjSso]2021-10-20 09:17:47,753-org.apache.ibatis.logging.LogFactory-104 [main]DEBUGorg.apache.ibatis.logging.LogFactory-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[lsjSso]2021-10-20 09:17:47,781-org.apache.ibatis.datasource.pooled.PooledDataSource-132 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections.
[lsjSso]2021-10-20 09:17:47,781-org.apache.ibatis.datasource.pooled.PooledDataSource-132 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections.
[lsjSso]2021-10-20 09:17:47,781-org.apache.ibatis.datasource.pooled.PooledDataSource-132 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections.
[lsjSso]2021-10-20 09:17:47,782-org.apache.ibatis.datasource.pooled.PooledDataSource-133 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections.
[lsjSso]2021-10-20 09:17:47,953-org.apache.ibatis.transaction.jdbc.JdbcTransaction-304 [main]DEBUGorg.apache.ibatis.transaction.jdbc.JdbcTransaction-Opening JDBC Connection
[lsjSso]2021-10-20 09:17:48,174-org.apache.ibatis.datasource.pooled.PooledDataSource-525 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-Created connection 16503286.
[lsjSso]2021-10-20 09:17:48,174-org.apache.ibatis.transaction.jdbc.JdbcTransaction-525 [main]DEBUGorg.apache.ibatis.transaction.jdbc.JdbcTransaction-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@fbd1f6]
[lsjSso]2021-10-20 09:17:48,177-com.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-528 [main]DEBUGcom.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-==>  Preparing: SELECT g.*,g.groupID AS groupno FROM teachergroup g WHERE g.groupid =? 
[lsjSso]2021-10-20 09:17:48,211-com.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-562 [main]DEBUGcom.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-==> Parameters: 1(Integer)
[lsjSso]2021-10-20 09:17:48,257-com.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-608 [main]DEBUGcom.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-<==      Total: 1
教研组编号:1,教研组名称:chinese
[lsjSso]2021-10-20 09:17:48,258-com.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-609 [main]DEBUGcom.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-==>  Preparing: SELECT * FROM teacher WHERE groupno = ? 
[lsjSso]2021-10-20 09:17一文搞定Mybatis 一对多延迟加载,并且子查询中与主表字段不对应

MyBatis一对多查询及延迟加载

mybatis 延迟加载学习

Mybatis学习总结——延迟加载

MyBatis学习--延迟加载

七 mybatis的延迟加载