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());}}
}

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

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

相关文章

Yield Guild Games 宣布与区块链游戏中心 Iskra 建立战略合作伙伴关系

Yield Guild Games (YGG) 宣布将向 Iskra 引入其任务系统&#xff0c;Iskra 是一个 Web3 游戏中心和发布平台&#xff0c;拥有超过 400 万注册钱包和 10 万月度活跃用户 (MAU)。在 LINE、Kakao、Wemade 和 Netmarble 等公司的支持下&#xff0c;Iskra 将游戏玩家和游戏工作室聚…

Java 内存模型深度解析

优质博文&#xff1a;IT-BLOG-CN 一、并发编程模型的两个关键问题 【1】并发中常见的两个问题&#xff1a;线程之间如何通信及线程之间如何同步。通信是指线程之间以何种机制来交换信息。在命令式编程中&#xff0c;线程之间的通信机制有两种&#xff1a;内存共享和消息传递&…

日常常见应用组件升级记录

一、前言 因近期安全扫描&#xff0c;发现java后端应用涉及多个引用组件版本过低&#xff0c;涉及潜在漏洞利用风险&#xff0c;特记录相关处理升级处理过程&#xff0c;以备后续确认&#xff1b; 二、升级处理过程 2.1、Java类应用内置Spring Boot版本升级 Spring Boot是一…

代码随想录算法训练营第十天|232 用栈实现队列、225 用队列实现栈

栈与队列 栈&#xff08;stack&#xff09;&#xff1a;先进后出&#xff1b;队列&#xff08;queue&#xff09;&#xff1a;先进先出栈和队列是STL里面的两个数据结构栈不能遍历元素&#xff0c;提供pop和push等接口&#xff0c;时间复杂度都为O(1)在SGI STL中&#xff0c;如…

python爬虫案例分享

当然&#xff0c;我可以分享一个基本的Python爬虫示例。这个示例将使用Python的requests库来抓取网页内容&#xff0c;然后使用BeautifulSoup库来解析和提取信息。我们将构建一个简单的爬虫来从一个示例网站抓取标题。 Python爬虫示例 目标 提取某网站的标题。 需要的库 r…

bug笔记:解决 HTTP Error 500.30 - ASP.NET Core app failed to start

总结下后端部署windos iis环境net6版本&#xff0c;500.30问题报错的一种解决方案&#xff1a; 一、问题描述 二、解决方案 检查下是否安装了net6对应的环境&#xff0c;是否已经安装 然后在事件管理器>Windows日志>应用程序&#xff0c;里面查看详细异常记录 在iis下面…

使用golang对接微软Azure AI翻译

文章目录 一、官方地址二、准备工作三、代码示例 一、官方地址 https://learn.microsoft.com/zh-CN/azure/ai-services/translator/translator-text-apis?tabsgo 二、准备工作 创建服务 创建服务连接地址&#xff1a;https://portal.azure.com/#create/Microsoft.CognitiveS…

RabbitMQ与SpringAMQP

MQ&#xff0c;中文是消息队列&#xff08;MessageQueue&#xff09;&#xff0c;字面来看就是存放消息的队列。也就是事件驱动架构中的Broker。&#xff08;经纪人&#xff01;&#xff09; 1.RabbitMQ介绍 微服务间通讯有同步和异步两种方式 同步&#xff08;通信&#xff0…

ruoyi-cloud—若依微服务打包部署

1. 前端端口修改 2. 后端端口修改 &#xff08;1&#xff09;修改ruoyi-gateway服务中的bootstrap.yml的port端口 &#xff08;2&#xff09;修改ruoyi-ui中的vue.confing.js的target中的端口 3. 后端部署 (1) 在本地电脑上代码界面上打包后端 在ruoyi项目的bin目录下执行pa…

探索 ChatGPT 中文版:开启自然语言处理新纪元

ChatGPT 中文版是一款由 OpenAI 推出的自然语言处理模型&#xff0c;它在中文语境下展现出了出色的文本生成和对话交互能力。作为程序员&#xff0c;我们对这一领域的创新和发展充满期待。 ChatGPT 中文版不仅能够回答各种技术问题&#xff0c;还能够生成代码示例&#xff0c;…

回溯法:N皇后问题

问题背景 八皇后问题是十九世纪著名的数学家高斯于1850年提出的。 • 问题是&#xff1a;在88的棋盘上摆放八个皇后&#xff0c; 使其不能互相攻击&#xff0c; 即任意两个皇后都不能处于同一行、 同一列或同一斜线上。 • n皇后问题&#xff1a;即在n n的棋盘上摆放n个皇后…

看完这篇我就不信还有人不懂卷积神经网络!

看完这篇我就不信还有人不懂卷积神经网络&#xff01; 前言 在深度学习大&#x1f525;的当下&#xff0c;我知道介绍卷积神经网络的文章已经在全网泛滥&#xff0c;但我还是想要写出一点和别人不一样的东西&#xff0c;尽管要讲的知识翻来覆去还是那么一些&#xff0c;但我想…

Redis原理篇(SkipList)

一.概述 本质是双端链表&#xff0c;只不过在正向遍历时可以不一个一个遍历&#xff0c;而是可以跳着遍历。 怎么实现的呢&#xff0c;下面是SkipList源码 二.源码 1. zskiplist 意义&#xff1a;跳表 zskiplist里面有头指针和尾指针&#xff0c;节点数量&#xff0c;最大…

【信号与系统】(1)连续和离散表示

在信号处理和数学中&#xff0c;连续和离散是两种基本的表示方法&#xff0c;用于描述信号、函数或数据集。 对连续信号 f(t)进行等间隔采样得到 连续表示&#xff08;Continuous Representation&#xff09; 连续表示通常用于描述在一个连续范围内变化的信号或函数。在连续…

Java学习(二十一)--JDBC/数据库连接池

为什么需要 传统JDBC数据库连接&#xff0c;使用DriverManager来获取&#xff1b; 每次向数据库建立连接时都要将Connection加载到内存中&#xff0c;再验证IP地址、用户名和密码&#xff08;0.05s~1s)时间。 需要数据库连接时候&#xff0c;就向数据库要求一个&#xf…

JS-WebAPIS(四)

日期对象&#xff08;常用&#xff09; • 实例化 在代码中发现了 new 关键字时&#xff0c;一般将这个操作称为实例化创建一个时间对象并获取时间 获得当前时间 获得指定时间 • 时间对象方法 使用场景&#xff1a;因为日期对象返回的数据我们不能直接使用&#xff0c;所以…

学习心得:二分查找

二分查找 基础:查找元素是否出现 #include <stdio.h> int main() {int a[10]{0,1,1,3,4,5,6,7,8,9},int x;scanf("%d",&x);int l0,r9,count0;while(l<r){int m(lr)/2;if(a[m]x){countm;break;}if(a[m]>x){rm-1;}if(a[m]<x)lm1;}printf("%d…

Elasticsearch 查询语句概述

目录 1. Match Query 2. Term Query 3. Terms Query 4. Range Query 5. Bool Query 6. Wildcard Query 7. Fuzzy Query 8. Prefix Query 9. Aggregation Query Elasticsearch 是一个基于 Lucene 的搜索引擎&#xff0c;提供了丰富的查询DSL&#xff08;Domain Specifi…

【2023我的编程之旅】七次不同的计算机二级考试经历分享

目录 我报考过的科目 第一次报考MS Office 第二次报考Web语言&#xff0c;C语言&#xff0c;C语言 第三次报考C语言&#xff0c;C语言&#xff0c;Java语言 分享一些备考二级的方法 一些需要注意的细节 结语 2023年的CSDN征文活动已经进入了尾声&#xff0c;在这最后我…

Excel·VBA合并工作簿2

其他合并工作簿的方法&#xff0c;见之前的文章《ExcelVBA合并工作簿》 目录 8&#xff0c;合并文件夹下所有工作簿中所有工作表&#xff0c;按表头汇总举例 8&#xff0c;合并文件夹下所有工作簿中所有工作表&#xff0c;按表头汇总 与之前的文章《ExcelVBA合并工作簿&#x…