mybatis中使用懶加載實現一對多復雜查詢


1.包結構

2.pom配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zy</groupId>
    <artifactId>mybatis03</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.21</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.16</version>
        </dependency>
    </dependencies>


</project>

3.main目錄下

3.1java目錄下

 3.1.1model層

===================stu類==========================
package com.zy.model;

import java.io.Serializable;

/**
 * Created by Administrator on 2018/6/27.
 */
public class Stu implements Serializable{

    private Integer id;
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Stu{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + 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 Integer getAge() {
        return age;
    }

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

    public Stu() {

    }

    public Stu(Integer id, String name, Integer age) {

        this.id = id;
        this.name = name;
        this.age = age;
    }
}
=========================classinfo類=================
package com.zy.model;

import java.io.Serializable;

/**
 * Created by Administrator on 2018/6/29.
 */
public class ClassInfo implements Serializable {

    private Integer id;
    private String className;

    @Override
    public String toString() {
        return "ClassInfo{" +
                "id=" + id +
                ", className='" + className + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public ClassInfo() {

    }

    public ClassInfo(Integer id, String className) {

        this.id = id;
        this.className = className;
    }
}
==============score類============================
package com.zy.model;

import java.io.Serializable;

/**
 * Created by Administrator on 2018/6/29.
 */
public class Score implements Serializable {

    private Integer id;
    private String sub;
    private Integer score;
    private Integer sId;

    public Integer getsId() {
        return sId;
    }

    public void setsId(Integer sId) {
        this.sId = sId;
    }

    public Score(Integer id, String sub, Integer score, Integer sId) {

        this.id = id;
        this.sub = sub;
        this.score = score;
        this.sId = sId;
    }

    @Override
    public String toString() {
        return "Score{" +
                "id=" + id +
                ", sub='" + sub + '\'' +
                ", score=" + score +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getSub() {
        return sub;
    }

    public void setSub(String sub) {
        this.sub = sub;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    public Score() {

    }

    public Score(Integer id, String sub, Integer score) {

        this.id = id;
        this.sub = sub;
        this.score = score;
    }
}

3.1.2dto層

==========studto類===================
package com.zy.dto;

import com.zy.model.ClassInfo;
import com.zy.model.Stu;

/**
 * Created by Administrator on 2018/6/29.
 */
public class StuDto extends Stu {

    private ClassInfo classInfo;

    public ClassInfo getClassInfo() {
        return classInfo;
    }

    public void setClassInfo(ClassInfo classInfo) {
        this.classInfo = classInfo;
    }

    public StuDto() {

    }

    public StuDto(ClassInfo classInfo) {

        this.classInfo = classInfo;
    }

    @Override
    public String toString() {
        return super.toString() + classInfo;
    }


}
============classinfodto類==========================
package com.zy.dto;

import com.zy.model.ClassInfo;
import com.zy.model.Stu;

/**
 * Created by Administrator on 2018/6/29.
 */
public class ClassInfoDto extends ClassInfo {

    private Stu stu;

    public ClassInfoDto(Stu stu) {
        this.stu = stu;
    }

    public ClassInfoDto() {
    }

    @Override
    public String toString() {
        return "ClassInfoDto{" +
                "stu=" + stu +
                '}';
    }

    public Stu getStu() {
        return stu;package com.zy.dto;

import com.zy.model.Score;
import com.zy.model.Stu;

import java.util.List;

/**
 * Created by Administrator on 2018/6/29.
 */
public class ScoreDto extends Stu {

    private List<Score> list;

    @Override
    public String toString() {
        return "ScoreDto{" +
                "list=" + list +
                "} " + super.toString();
    }

    public List<Score> getList() {
        return list;
    }

    public void setList(List<Score> list) {
        this.list = list;
    }

    public ScoreDto(List<Score> list) {

        this.list = list;
    }

    public ScoreDto() {

    }
}

    }

    public void setStu(Stu stu) {
        this.stu = stu;
    }
}
==================ScoreDto類==================

3.1.3mapper層

===============StuMapper接口===================
package com.zy.mapper;

import com.zy.dto.ClassInfoDto;
import com.zy.dto.ScoreDto;
import com.zy.model.Stu;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Created by Administrator on 2018/6/27.
 */

public interface StuMapper {

    // 根據班級id獲取學生信息
    List<Stu> getStuByClassId(@Param("id") Integer id);

    // 分步查詢(一對一):即多個單表查詢,一個查詢結果是另一個查詢的條件:需要配置懶加載,並關閉延遲加載
    List<ClassInfoDto> getStuByClassIdStep(@Param("id") Integer id);

    // 分步查詢(一對多):即多個單表查詢,一個查詢結果是另一個查詢的條件:需要配置懶加載,並關閉延遲加載
    List<ScoreDto> getStuByScoreStep(@Param("id") Integer id);

}
===================ClassInfoMapper接口=================
package com.zy.mapper;

import com.zy.model.ClassInfo;
import org.apache.ibatis.annotations.Param;

/**
 * Created by Administrator on 2018/6/29.
 */
public interface ClassInfoMapper {

    // 根據班級id查詢班級信息
    ClassInfo getClassById(@Param("cid") Integer id);
}
==================ScoreMapper接口=============
由於是最后一層,可寫可不寫方法,但接口一定要定義!!!!!!!!!!!!!!!

3.1.4util層(用於Junit測試)

package com.zy.util;

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

import java.io.InputStream;

/**
 * Created by Administrator on 2018/6/27.
 */
public class MybatisUtil {

    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;

    static {
        InputStream is = MybatisUtil.class.getClassLoader().getResourceAsStream("sqlMappingConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }

    /*定義或者sqlSession的方法*/
    public static SqlSession getSqlSession() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession(true);
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    /*定義關閉方法*/
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
}

3.2resources目錄下

3.2.1sqlMappingConfig.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>
    <!--讀取配置文件-->
    <properties resource="db.properties"/>
    <!--設置全局配置環境-->
    <settings>
        <!--開啟全局緩存-->
        <setting name="cacheEnabled" value="true"/>
        <!--開啟懶加載-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--根據對象觸發配置需要關閉-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <!--配置別名:不推薦使用-->
    <typeAliases></typeAliases>
    <!--配置數據庫環境-->
    <environments default="mysql_dev">
        <environment id="mysql_dev">
            <!--事務管理-->
            <transactionManager type="JDBC"></transactionManager>
            <!--數據庫-->
            <!--POOLED,UNPOOLED,JNDI-->
            <dataSource type="POOLED">
                <property name="url" value="${jdbc.url}"/>
                <property name="driver" value="${jdbc.driver}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射文件,mappers:將sql映射注冊到全局配置中-->
    <mappers>
        <package name="com.zy.mapper"/>
    </mappers>
</configuration>

3.2.2db.properties配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/atguigu_mybatis
jdbc.username=root
jdbc.password=123456

orcl.driver=oracle.jdbc.OracleDriver
orcl.url=jdbc:oracle:thin:@localhost:1521:orcl
orcl.username=zhang
orcl.password=123456

3.2.3其他xml配置

=============StuMapper.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">
<!--
namespace:名稱空間;指定為接口的全類名
id:唯一標識
resultType:返回值類型
#{id}:從傳遞過來的參數中取出id值

public Employee getEmpById(Integer id);
-->


<!--namespace必須是EmployeeMapper的全限定名-->
<mapper namespace="com.zy.mapper.StuMapper">
    <!--配置resultMap:關聯查詢-->
    <resultMap id="stuResultMap" type="com.zy.dto.StuDto">
        <!--如果是date類型的變量,此處的jdbcType必須配置為TIMESTAMP-->
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
        <association property="classInfo" javaType="com.zy.model.ClassInfo">
            <id column="id" property="id"/>
            <result column="className" property="className"/>
        </association>
    </resultMap>

   <!--配置resultMap(一對一):分步查詢-->
    <resultMap id="stuResultMapStep" type="com.zy.dto.StuDto">
        <!--如果是date類型的變量,此處的jdbcType必須配置為TIMESTAMP-->
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
        <association property="classInfo" javaType="com.zy.model.ClassInfo" select="com.zy.mapper.ClassInfoMapper.getClassById" column="cid"/>
    </resultMap>

   <!--配置resultMap(一對多):分步查詢-->
    <resultMap id="stuResultMapScoreStep" type="com.zy.dto.ScoreDto">
        <!--如果是date類型的變量,此處的jdbcType必須配置為TIMESTAMP-->
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
        <collection property="list" ofType="com.zy.model.Score" select="com.zy.mapper.ScoreMapper.getScoreById" column="id" />
    </resultMap>


<!--==================查詢結果區====================-->

    <!--// 根據班級id獲取學生信息
    Stu getStuByClassId(Integer id);-->
    <select id="getStuByClassId" resultMap="stuResultMap">
        SELECT s.id id,s.`name` name,s.age age,c.className className
        from t_stu s
        LEFT JOIN t_classinfo c
        on s.cId = c.id
        where c.id = #{id}
    </select>

    <!--// 分步查詢:即多個單表查詢,一個查詢結果是另一個查詢的條件:需要配置懶加載,並關閉延遲加載
    List<Stu> getStuByClassIdStep(@Param("id") Integer id);-->
    <select id="getStuByClassIdStep" resultMap="stuResultMapStep">
        select * from t_stu where id=#{id}
    </select>

    <!--// 分步查詢(一對多):即多個單表查詢,一個查詢結果是另一個查詢的條件:需要配置懶加載,並關閉延遲加載
    List<Stu> getStuByScoreStep(@Param("id") Integer id);-->

    <select id="getStuByScoreStep" resultMap="stuResultMapScoreStep">
        select * from t_stu where id=#{id}
    </select>




</mapper>
===================ClassInfoMapper.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.zy.mapper.ClassInfoMapper">
    <select id="getClassById" resultType="com.zy.model.ClassInfo">
        select * from classInfo where id = #{cid}
    </select>
</mapper>
================ScoreMapper.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.zy.mapper.ScoreMapper">
    <!--定義resultMap-->
    <resultMap id="myScoreResultMap" type="com.zy.model.Score">
        <id column="id" property="id"/>
        <result column="sub" property="sub"/>
        <result column="score" property="score"/>
        <result column="sId" property="sId"/>
    </resultMap>
    <select id="getScoreById" resultMap="myScoreResultMap">
        SELECT * from t_score where sId = #{id}
    </select>
</mapper>

4.junit測試配置

import com.zy.dto.ClassInfoDto;
import com.zy.dto.ScoreDto;
import com.zy.mapper.StuMapper;
import com.zy.model.Stu;
import com.zy.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * Created by Administrator on 2018/6/29.
 */
public class StuTest {

    // 按照班級id查詢
    @Test
    public void testGetStuById() {
        // 獲取sqlSession
        final SqlSession sqlSession = MybatisUtil.getSqlSession();
        // 獲取mapper
        StuMapper mapper = sqlSession.getMapper(StuMapper.class);
        // 調用mapper的增加方法
        List<Stu> list = mapper.getStuByClassId(1);
        System.out.println(list);
        // 關閉資源
        MybatisUtil.closeSqlSession();
    }

    // 分步查詢:即多個單表查詢,一個查詢結果是另一個查詢的條件:需要配置懶加載,並關閉延遲加載
    @Test
    public void testGetStuByClassIdStep() {
        // 獲取sqlSession
        final SqlSession sqlSession = MybatisUtil.getSqlSession();
        // 獲取mapper
        StuMapper mapper = sqlSession.getMapper(StuMapper.class);
        // 調用mapper的增加方法
        List<ClassInfoDto> list = mapper.getStuByClassIdStep(1);
        System.out.println(list);
        // 關閉資源
        MybatisUtil.closeSqlSession();
    }

    // 分步查詢:即多個單表查詢,一個查詢結果是另一個查詢的條件:需要配置懶加載,並關閉延遲加載
    @Test
    public void testGetStuByScoreStep() {
        // 獲取sqlSession
        final SqlSession sqlSession = MybatisUtil.getSqlSession();
        // 獲取mapper
        StuMapper mapper = sqlSession.getMapper(StuMapper.class);
        // 調用mapper的增加方法
        List<ScoreDto> list = mapper.getStuByScoreStep(1);
        System.out.println(list);
        // 關閉資源
        MybatisUtil.closeSqlSession();
    }




}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM