文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2023-05-14 05:27

关注

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

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

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

image-20230326141952875

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

image-20230331151146829

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/POM/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.8.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>
        </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>***.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" value="${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;


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;


@Data
public class Teacher {
    private int id;
    private String name;
}

Student.java

package com.sun.pojo;

import lombok.Data;


@Data
public class Student {
    private int id;
    private String name;
}

Classes.java

package com.sun.pojo;

import lombok.Data;

import java.util.List;


@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;


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.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


public class MapperTest {
    
    @Test
    public 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:

image-20230331151047498

test2:

image-20230331151113226

总结:一对一关联查询需要在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关联查询内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯