开发者

Mybatis实现一对一、一对多关联查询的方法(示例详解)

MyBATis实现一对一、一对多关联查询,关联查询:多个表联合查询,只查询一次,通过resultMap里面的<association><collection>标签配置一对一、一对多。

涉及的sql文件、idea工程文件:Mybatis实现一对一、一对多关联查询资源

本篇文章涉及的一对一、一对多关系

  • 班级classes、班主任teacher是一对一的关系
  • 班级classes、学生student是一对多的关系

Mybatis实现一对一、一对多关联查询的方法(示例详解)

使用IDEA快速构建一个MyBatis工程

Mybatis实现一对一、一对多关联查询的方法(示例详解)

pom.XML

<?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/Phttp://www.devze.comOM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com</groupId>
    <artifactId>sun</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>mybatisTest</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <junit.version>5.8python.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-Java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        <www.devze.com;/dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <!-- directory:指定资源文件的位置 -->
                <directory>src/main/java</directory>
                <includes>
                    <!-- “**” 表示任意级目录    “*”表示任意任意文件 -->
                    <!-- mvn resources:resources :对资源做出处理,先于compile阶段  -->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <!--  filtering:开启过滤,用指定的参数替换directory下的文件中的参数(eg. ${name}) -->
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>
</project>

mybatis-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">

<!-- 通过这个配置文件完成mybatis与数据库的连接 -->
<configuration>
    <!-- 引入 database.properties 文件-->
    <properties resource="database.properties"/>

    <!-- 配置mybatis的log实现为LOG4J -->
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>

    <environments default="development">
        <environment id="development">
            <!--配置事务管理,采用JDBC的事务管理  -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED:mybatis自带的数据源,JNDI:基于tomcat的数据源 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" va编程lue="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 将mapper文件加入到配置文件中 -->
    <mappers>
        <mapper resource="com/sun/mapper/ClassesMapper.xml"/>
    </mappers>
</configuration>

database.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
user=root
password=root

MybatisUtil.java

package com.sun.utils;

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.InputStream;

/**
 * @author JumperSun
 * @date 2023-03-26-14:46
 */
public class MyBatisUtil {
    private static SqlSessionFactory factory;

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession createSqlSession(){
        return factory.openSession(false); // true为自动提交事务
    }

    public static void closeSqlSession(SqlSession sqlSession){
        if(null != sqlSession)
            sqlSession.close();
    }
}

Teacher.java

package com.sun.pojo;

import lombok.Data;

/**
 * @author JumperSun
 * @date 2023-03-26-14:51
 */
@Data
public class Teacher {
    private int id;
    private String name;
}

Student.java

package com.sun.pojo;

import lombok.Data;

/**
 * @author JumperSun
 * @date 2023-03-26-14:53
 */
@Data
public class Student {
    private int id;
    private String name;
}

Classes.java

package com.sun.pojo;

import lombok.Data;

import java.util.List;

/**
 * @author JumperSun
 * @date 2023-03-26-14:52
 */
@Data
public class Classes {
    private int id;
    private String name;
    private Teacher teacher;
    private List<Student> studentList;
}

classMapper.java

package com.sun.mapper;

import com.sun.pojo.Classes;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author JumperSun
 * @date 2023-03-26-14:54
 */
public interface ClassesMapper {
    List<Classes> getClassesTeacher(@Param("id") int id);

    List<Classes> getClassesTeacherStudentList(@Param("id") int id);
}

classMapper.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.sun.mapper.ClassesMapper">

    <!-- 一对一关联查询 -->
    <select id="getClassesTeacher" parameterType="int" resultMap="ClassesResultMap">
        select * from classes c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
    </select>

    <resultMap type="com.sun.pojo.Classes" id="ClassesResultMap">
        <!-- 实体类的字段名和数据表的字段名映射 -->
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <association property="teacher" javaType="com.sun.pojo.Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
    </resultMap>

    <!-- 一对多关联查询 -->
    <select id="getClassesTeacherStudentList" parameterType="int" resultMap="ClassesResultMap2">
        select * from classes c,teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id}
    </select>

    <resultMap type="com.sun.pojo.Classes" id="ClassesResultMap2">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <association property="teacher" javaType="com.sun.pojo.Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
        <collection property="studentList" ofType="com.sun.pojo.Student">
            <id property="id" column="s_id"/>
            <result property="name" column="s_name"/>
        </collection>
    </resultMap>

</mapper>

MapperTest.java

import com.sun.mapper.ClassesMapper;
import com.sun.pojo.Classes;
import com.sun.utils.MyBatisUtil;
import org.apache.ibati开发者_开发教程s.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @author JumperSun
 * @date 2023-03-26-15:10
 */
public class MapperTest {
    /**
     * 测试班级与班主任老师一对一的关联关系
     */
    @Test
    publphpic void test1() {
        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        ClassesMapper classesMapper = sqlSession.getMapper(ClassesMapper.class);
        List<Classes> classes = classesMapper.getClassesTeacher(1);
        for (Classes Classes : classes) {
            System.out.println(classes);
        }

    }

    /**
     * 测试班级与学生一对多关联关系
     */
    @Test
    public void test2() {
        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        ClassesMapper classesMapper = sqlSession.getMapper(ClassesMapper.class);
        List<Classes> classes = classesMapper.getClassesTeacherStudentList(1);
        for (Classes Classes : classes) {
            System.out.println(classes);
        }

    }
}

test1:

Mybatis实现一对一、一对多关联查询的方法(示例详解)

test2:

Mybatis实现一对一、一对多关联查询的方法(示例详解)

总结:一对一关联查询需要在resultMap里面配置association,一对多关联查询需要在resultMap里面配置collection;

List classes = classesMapper.getClassesTeacherStudentList(1);
for (Classes Classes : classes) {
System.out.println(classes);
}}

}
test1:
[外链图片转存中...(img-qon5qYiR-1680248446105)]
test2:
[外链图片转存中...(img-dzayGx8q-1680248446107)]
总结:一对一关联查询需要在resultMap里面配置association,一对多关联查询需要在resultMap里面配置collection;

到此这篇关于Mybatis实现一对一、一对多关联查询的方法(示例详解)的文章就介绍到这了,更多相关Mybatis关联查询内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜