当前位置: 首页 > news >正文

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

项目结构

在这里插入图片描述

数据库表

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;}@Overridepublic 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;}@Overridepublic 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 configurationPUBLIC "-//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 mapperPUBLIC "-//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 mapperPUBLIC "-//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_idwhere 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 {@Testpublic 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);}}@Testpublic 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 {@Testpublic 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();}@Testpublic 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);}}@Testpublic 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();}@Testpublic 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();}@Testpublic 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());}}@Testpublic 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());}}
}

相关文章:

  • Git学习笔记(第1章):Git概述
  • RDMA Scatter Gather List详解
  • Go 日期时间包装器:15条更便捷的时间处理
  • (学习日记)2024.01.19
  • C++:史上最坑小游戏
  • 【RabbitMQ】快速入门及基本使用
  • C#,字符串匹配(模式搜索)有限自动机(Finite Automata)算法的源代码
  • 配置中心原理和选型
  • Python文件自动化处理
  • vue 解决el-table 表体数据发生变化时,未重新渲染问题
  • 代码随想录算法训练53 | 动态规划part14
  • 带你学C语言-指针(4)
  • cetos7搭建部署k8s 版本1.28
  • Docker进阶篇-安装MySQL主从复制
  • nestjs之provider的provide取值的几种方式
  • 收藏网友的 源程序下载网
  • [数据结构]链表的实现在PHP中
  • Android开源项目规范总结
  • es6(二):字符串的扩展
  • JAVA 学习IO流
  • Js基础——数据类型之Null和Undefined
  • Protobuf3语言指南
  • 初识MongoDB分片
  • 前端之Sass/Scss实战笔记
  • 体验javascript之美-第五课 匿名函数自执行和闭包是一回事儿吗?
  • 怎么把视频里的音乐提取出来
  • #include
  • #QT(TCP网络编程-服务端)
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (39)STM32——FLASH闪存
  • (阿里巴巴 dubbo,有数据库,可执行 )dubbo zookeeper spring demo
  • (保姆级教程)Mysql中索引、触发器、存储过程、存储函数的概念、作用,以及如何使用索引、存储过程,代码操作演示
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一
  • .net 8 发布了,试下微软最近强推的MAUI
  • .NET Core WebAPI中使用swagger版本控制,添加注释
  • .net core使用RPC方式进行高效的HTTP服务访问
  • .NET 设计一套高性能的弱事件机制
  • @Autowired多个相同类型bean装配问题
  • @Not - Empty-Null-Blank
  • @Tag和@Operation标签失效问题。SpringDoc 2.2.0(OpenApi 3)和Spring Boot 3.1.1集成
  • [2013AAA]On a fractional nonlinear hyperbolic equation arising from relative theory
  • [2019/05/17]解决springboot测试List接口时JSON传参异常
  • [BT]BUUCTF刷题第8天(3.26)
  • [BUG]Datax写入数据到psql报不能序列化特殊字符
  • [Bugku]密码???[writeup]
  • [C++]——带你学习类和对象
  • [CareerCup] 13.1 Print Last K Lines 打印最后K行
  • [C语言]编译和链接
  • [Django 0-1] Core.Handlers 模块
  • [EFI]Atermiter X99 Turbo D4 E5-2630v3电脑 Hackintosh 黑苹果efi引导文件
  • [FFmpeg学习]从视频中获取图片
  • [github配置] 远程访问仓库以及问题解决
  • [ISCTF 2023]——Web、Misc较全详细Writeup、Re、Crypto部分Writeup
  • [javascript]Tab menu实现