mybatis xml多表查询,子查询,连接查询,动态sql

news2024/9/22 23:16:16

项目结构

在这里插入图片描述

数据库表

student_type 表

在这里插入图片描述

student 表

在这里插入图片描述

依赖

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

实体类

Student 类

一个学生只有一个年级

package com.tmg.domain;

public class Student {
    private int id;
    private String name;
    private int age;
    private String email;
    private Integer typeId;
    private Type type;

    public Integer getTypeId() {
        return typeId;
    }

    public void setTypeId(Integer typeId) {
        this.typeId = typeId;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Student(int id, String name, int age, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public Student() {
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", typeId=" + typeId +
//                ", type=" + type +
                '}';
    }
}

Type 类

一个年级有多个学生,所以用 list

package com.tmg.domain;

import java.util.List;

public class Type {
    private Integer id;
    private String name;
    private List<Student> students;

    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 List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Type{" +
                "id=" + id +
                ", name='" + name + '\'' +
//                ", students=" + students +
                '}';
    }
}

StudentDao

package com.tmg.dao;

import com.tmg.domain.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface StudentDao {


    //多个参数的配置
    void insertEmp( @Param("stuName")  String name,
                   @Param("stuAge") int age, @Param("stuEmail")  String email);

    List<Student> selectByStudent(Student student);

    void update(Student employee);

    void update2(Student employee);

    List<Student> selectByIds(@Param("ids") int []id);
//    List<Student> selectById(int id);

    List<Student> selectByTypeId(int id);
    List<Student> selectAll();
}

TypeDao

package com.tmg.dao;

import com.tmg.domain.Type;

import java.util.List;

public interface TypeDao {

    List<Type> selectAll();

    Type  selectById(Integer id);
}

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">
<configuration>
<!--    dddd-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="ture"/><!--配置下划线转换为驼峰命名风格-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager><!--事务管理器-->
            <dataSource type="POOLED"><!--数据源 POOLED代表池化-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="dao/StudentDao.xml"></mapper>
        <mapper resource="dao/TypeDao.xml"></mapper>
    </mappers>
</configuration>

TypeDao.xml

下列代码中:
1 resultMap 里面property对应实体类属性,column对应数据库字段名
2 主键用 id 标签 其他用result
3 关联查询(子查询和连接查询) 连接查询查一次
4 一个年级多个学生,所以用collection 如果一对一用association

<?xml version="1.0" encoding="UTF-8" ?>

<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tmg.dao.TypeDao">
    <resultMap id="typeMap" type="com.tmg.domain.Type">
        <id property="id" column="type_id"></id>
        <result property="name" column="type_name"></result>
<!--        连接查询-->
<!--        <collection property="students"-->
<!--                    javaType="java.util.List" ofType="com.tmg.domain.Student">-->
<!--            <id property="id" column="stu_id" javaType="java.lang.Integer"></id>-->
<!--            <result property="name" column="stu_name"></result>-->
<!--            <result property="age" column="stu_age"></result>-->
<!--            <result property="email" column="stu_email"></result>-->
<!--        </collection>-->

<!--        子查询-->
        <collection property="students" column="type_id"
                    javaType="java.util.List" ofType="com.tmg.domain.Student"
                    select="com.tmg.dao.StudentDao.selectByTypeId">

        </collection>
<!-- property 实体类中的属性名 column 子查询使用的字段 javaType 集合类型  ofType 集合里面的泛型类型-->
    </resultMap>
    <select id="selectAll" resultMap="typeMap">
        select s.*,t.* from student s join student_type t on s.type_id=t.type_id
    </select>

    <select id="selectById" resultMap="typeMap">
        select * from student_type where type_id=#{id}
    </select>


</mapper>

StudentDao.xml

动态sql不理解可看以下博客:
https://blog.csdn.net/weixin_57689217/article/details/135707991?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22135707991%22%2C%22source%22%3A%22weixin_57689217%22%7D

<?xml version="1.0" encoding="UTF-8" ?>

<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射的命名空间 = 包名+接口类-->
<mapper namespace="com.tmg.dao.StudentDao">
    <!--配置insert操作 id是方法名 parameterType是参数类型  #{属性名}用于读取对象的属性值-->
    <!--#{}和${}的区别,#{}相当于PreparedStatement的占位符?提前编译,避免SQL注入 ${}是Statement字符串拼接,不能避免注入 -->
    <!--获得最新的自增主键值 useGeneratedKeys=true keyProperty主键的属性-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into student( id,name,age,email) values (#{id},#{name},#{age},#{email});
    </insert>

<!--    问题:查询出的名称为多个单词的字段出现null值-->
<!--    原因:数据库的字段单词以下划线分隔,Java的属性以驼峰命名,导致部分名称不一致无法实现映射-->
    <select id="selectAll" resultMap="student">
        select * from student
    </select>

    <resultMap id="student" type="com.tmg.domain.Student">
        <!--配置主键 property是java属性名 column是表字段名-->
        <id property="id" column="stu_id" javaType="java.lang.Integer"></id>
        <!--普通字段-->
        <result property="name" column="stu_name"></result>
        <result property="age" column="stu_age"></result>
        <result property="email" column="stu_email"></result>
        <result property="typeId" column="type_id"></result>

<!--        <association property="type"-->
<!--                     javaType="com.tmg.domain.Type">-->
<!--            <id property="id" column="type_id"></id>-->
<!--            <result property="name" column="type_name"></result>-->
<!--        </association>-->
        <association property="type" column="type_id"
                     javaType="com.tmg.domain.Type"
                     select="com.tmg.dao.TypeDao.selectById">

        </association>
    </resultMap>


<!--    动态sql-->
<sql id="mySelect">
    select * from student
</sql>
    <select id="selectByStudent" parameterType="com.tmg.domain.Student" resultType="com.tmg.domain.Student" resultMap="student">
        <include refid="mySelect"></include>
        <where>
            <if test="name !=null">

                stu_name like "%"#{name}"%"
            </if>
            <if test="age !=null and age!=0">
                and stu_age=#{age}
            </if>
            <if test="email !=null">
                and stu_email=#{email}
            </if>
        </where>
    </select>

    <update id="update">
        update student
        <set>
            <if test="age !=null and age!=0">
                stu_age=#{age},
            </if>
            <if test="email!=null">
                stu_email=#{email},
            </if>
            <if test="name">
                stu_name=#{name},
            </if>
        </set>
        where stu_id=#{id};
    </update>
    <update id="update2">
        update student
        <trim prefix="set" suffixOverrides=",">
            <if test="age !=null and age!=0">
                stu_age=#{age},
            </if>
            <if test="email!=null">
                stu_email=#{email},
            </if>
            <if test="name">
                stu_name=#{name},
            </if>
        </trim>
        where stu_id=#{id};
    </update>

    <select id="selectByIds" resultMap="student">
        select s.*,t.* from student s join student_type t on s.type_id=t.type_id
        where stu_id in
        <foreach collection="ids" item="id" separator="," open="(" close=")" index="1">
            #{id}
        </foreach>
    </select>

    <select id="selectByTypeId" resultMap="student">
        <include refid="mySelect"></include> where type_id=#{id}
    </select>



</mapper>

TypeDaoText 测试类

package com.tmg.dao;

import com.tmg.domain.Type;
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.junit.Test;

import java.io.IOException;
import java.util.List;

public class TypeDaoText {
    @Test
    public void testselectAll() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        TypeDao mapper = sqlSession.getMapper(TypeDao.class);
        List<Type> typeList = mapper.selectAll();
        for (Type type : typeList) {
            System.out.println(type);
        }
    }


    @Test
    public void testselectById() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        TypeDao mapper = sqlSession.getMapper(TypeDao.class);
        Type type = mapper.selectById(1);
        System.out.println(type);
    }
}

StudentDaoText 测试类

package com.tmg.dao;

import com.tmg.domain.Student;
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.junit.Test;

import java.io.IOException;
import java.util.List;

public class StudentDaoText {

    @Test
    public void testinsertEmp() throws IOException {
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = factory.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        mapper.insertEmp("tmg",18,"tmg@qq.com");
        sqlSession.commit();
    }

    @Test
    public void testselectByStudent() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
//        student.setName("z");
//        student.setAge(18);
//        student.setEmail("tmg@qq.com");
        List<Student> students = mapper.selectByStudent(student);
        for (Student student1 : students){
            System.out.println(student1);
        }
    }
    @Test
    public void testupdate() throws IOException {
        //创建会话工厂构建器
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        //创建会话
        SqlSession sqlSession = build.openSession();
        //获得Mapper对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
//        student.setName();
        student.setId(1);
        student.setAge(22);
        mapper.update(student);
        sqlSession.commit();
    }
    @Test
    public void testupdate2() throws IOException {
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
        student.setId(1);
        student.setAge(44);
        mapper.update2(student);
        sqlSession.commit();
    }

    @Test
    public void testselectByIds() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        int []a={1};
        List<Student> students = mapper.selectByIds(a);
        for (Student student:students){
            System.out.println(student);
            System.out.println(student.getType());
        }
    }
    @Test
    public void testselectAll() throws IOException {
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        List<Student> students = mapper.selectAll();
        for(Student student : students){
            System.out.println(student);
            System.out.println(student.getType());
        }

    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1398123.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

cetos7搭建部署k8s 版本1.28

主机分配 内存最少是4G cpu个数最少两个 IP内存CPU主机名192.168.231.12044K1 192.168.231.12144K2192.168.231.12244K3 关闭防火墙 systemctl stop firewalled 关闭swap vim /etc/fstab 设置主机名称 hostnameset 安装docker 三个主机 初始化集群 在mas…

音乐人声分离工具:极简的人声和背景音乐分离工具

项目地址&#xff1a;jianchang512/vocal-separate: an extremely simple tool for separating vocals and background music, completely localized for web operation, using 2stems/4stems/5stems models 这是一个极简的人声和背景音乐分离工具&#xff0c;本地化网页操作&a…

鉴源实验室|自动驾驶仿真测试技术分析

01 引言 随着科技的不断发展&#xff0c;自动驾驶技术逐渐成为汽车行业的热门话题。然而&#xff0c;要将自动驾驶车辆投放到真实道路上之前&#xff0c;必须进行广泛的测试&#xff0c;以确保其在各种情况下都能安全可靠地运行。自动驾驶车辆的测试是一个复杂而昂贵的过程。…

Flink Kubernetes Operator 介绍

一、简介 Flink Kubernetes Operator是针对在Kubernetes上运行Apache Flink应用程序而设计的工具。它充分利用了Kubernetes的优势&#xff0c;实现了对Flink集群的弹性管理和自动化操作&#xff0c;通过扩展Kubernetes API的方式&#xff0c;提供了管理和操作Flink部署的功能。…

C语言——详解字符函数和字符串函数(上)

目录 一、strlen的使用和模拟实现 1.strlen()函数的介绍 2.strlen()函数的具体使用 3.strlen函数的注意事项 4.strlen函数的模拟实现 二、strcpy的使用和模拟实现 1.strcpy()函数的介绍 2.strcpy()函数的具体使用 3.strcpy()函数的注意事项 4.strcpy函数的模拟实现 …

【MySQL自身的性能优化】InnoDB 的 Buffer Pool

这里写目录标题 一、引入缓存的重要性二、InnoDB 的 Buffer Pool1. Buffer Pool 内部组成2. free 链表管理空闲页3. flush 链表管理脏页4. LRU 链表提高缓存命中那咱需要咋地解决预读问题呢&#xff1f;那咱需要咋地解决 Buffer Pool 污染问题呢&#xff1f; 5. 脏页什么时候被…

Spring Cloud可视化智慧工地大数据云平台源码(人、机、料、法、环五大维度)

智慧工地平台是依托物联网、互联网、AI、可视化建立的大数据管理平台&#xff0c;是一种全新的管理模式&#xff0c;能够实现劳务管理、安全施工、绿色施工的智能化和互联网化。围绕施工现场管理的人、机、料、法、环五大维度&#xff0c;以及施工过程管理的进度、质量、安全三…

鸿蒙harmony--数据库sqlite详解

今天是1月20号星期六&#xff0c;早安&#xff0c;岁末大寒至&#xff0c;静后春归来。愿他乡故人&#xff0c;漂泊有归宿&#xff0c;前程有奔赴&#xff0c;愿人间不寒&#xff0c;温暖常伴&#xff0c;诸事顺利&#xff0c;喜乐长安。 目录 一&#xff0c;定义 二&#xff…

Python seaborn库的边框设置(Seaborn篇-02)

Python seaborn库的边框设置(Seaborn篇-02)         🍹博主 侯小啾 感谢您的支持与信赖。☀️ 🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔…

Swin版VMamba来了!精度再度提升,VMamba-S达成83.5%,超越Swin-S,已开源!

本文首发&#xff1a;AIWalker 就在昨日&#xff0c;华科王兴刚团队公开了Mamba在ViT的入局Vim&#xff0c;取得了更高精度、更快速度、更低显存占用。相关信息可参考&#xff1a; 入局CV&#xff0c;Mamba再显神威&#xff01;华科王兴刚团队首次将Mamba引入ViT&#xff0c;更…

钡铼 楼宇暖通网关之 BACnet网关在空气源热泵智能控制系统中的应用介绍

前言 在刚刚过去的2023年&#xff0c;空气源热泵市场依然火爆&#xff0c;全线市场销量递增&#xff0c;各种新品层出不穷&#xff0c;市场认可度持续攀升&#xff0c;在整个采暖市场&#xff0c;空气源热泵已然成为当红明星。 热泵组管道比较复杂&#xff0c;传感器分布比较分…

vue2 使用pdf.js 实现pdf预览,并可复制文本

需求&#xff1a;pdf预览&#xff0c;并且可以选中pdf的内容进行复制。 在ruoyi的vue前端项目中用到&#xff0c;参考了网上不少文章&#xff0c;因为大部分没给具体的pdf.js版本&#xff0c;导致运行过程中报各种api 错误&#xff0c;经过尝试以下版本可用&#xff0c…

Linux中的新建用户、切换用户

目录 一、Linux系统中有哪些用户 二、新建普通用户 三、root账号与普通账号的切换 一、Linux系统中有哪些用户 1.root 超级管理员&#xff08;不受权限约束&#xff09; 2.其他用户 普通用户&#xff08;受到权限约束&#xff09; 二、新建普通用户 创建新用户 sudo user…

HarmonyOS鸿蒙学习基础篇 - 项目目录和文件介绍

vue_basic├── hvigor //存储购置信息的文件&#xff0c;主要用于发布打包 ├── idea //开发工具相关配置可忽略 ├── AppScope //工程目录 全局公共资源存放路径 │ └── resources │ │ └── base │ │ │ └── element //常亮存放 │ │ …

2023年中国互联网测试开发大会(MTSC2023上海站):核心内容与学习收获(附大会核心PPT下载)

在当今快速发展的互联网时代&#xff0c;软件质量与用户体验的保障离不开测试开发工程师的辛勤付出。本次峰会正是在这样的背景下应运而生&#xff0c;旨在汇聚业界精英&#xff0c;共同探讨测试开发的最新技术与实践。本文将深入剖析大会的核心内容&#xff0c;以及参与者从中…

零日漏洞:威胁与应对

一、引言 随着信息技术的迅猛发展&#xff0c;网络安全问题日益凸显。其中&#xff0c;零日漏洞已成为当今网络安全领域最受关注的问题之一。本文将深入探讨零日漏洞的威胁、产生原因以及应对策略&#xff0c;以期提高人们对这一问题的认识和防范意识。 二、零日漏洞的威胁 …

elementUI+el-upload 上传、下载、删除文件以及文件展示列表自定义为表格展示

Upload 上传组件的使用 官方文档链接使用el-upload组件上传文件 具体参数说明&#xff0c;如何实现上传、下载、删除等功能获取文件列表进行file-list格式匹配代码 文件展示列表自定义为表格展示 使用的具体参数说明文件大小展示问题&#xff08;KB/MB&#xff09;文件下载代码…

Ubuntu中查看IP地址的常用命令及使用方法

在Ubuntu操作系统中&#xff0c;了解和查看IP地址是进行网络配置、故障排除以及连接其他设备的重要一步。 以下是几个常用的命令来查看IP地址&#xff1a; 一、ifconfig命令 输入ifconfig 输出如图所示&#xff0c;即为ip地址 如若提示没有ifconfig命令&#xff0c;则可以使用…

node.js(expree.js )模拟手机验证码功能及登录功能

dbconfig.js const mysql require(mysql) module.exports {// 数据库配置config: {host: localhost, // 连接地址port: 3306, //端口号user: root, //用户名password: wei630229, //密码database: exapp2, //数据库名}, // 连接数据库&#xff0c;使用mysql的连接池连接方式…

力扣36. 有效的数独

模拟 思路&#xff1a; 使用三个哈希表来存储数字个数 row[r][val] 用于存储第 r 行 val 1 的个数&#xff1b;column[c][val] 用于存储第 c 列 val 1 的个数&#xff1b; subboxes[i][j][val] 用于存储第 i 行、第 j 列个小九宫格 val 1 的个数&#xff0c;其中&#xff1…