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.hqwc.cn/news/416448.html

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

相关文章

使用zabbix-proxy进行分布式监控

目录 一、准备4台服务器 二、配置主从复制 1.准备环境 2.主机名解析 3.安装数据库 4.配置主库db1 5.配置从库db2 6.主从状态显示 三、db1&#xff0c;db2配置zabbix-agent 三、zabbix-server的配置 四、zabbix-proxy的配置 1.为您的平台安装和配置Zabbix-proxy a. …

beego的模块篇 - I18n国际化

1. i18n 安装导入 安装该模块&#xff1a; go get github.com/beego/i18n 导入引用包&#xff1a; import ("github.com/beego/i18n" ) conf 目录下就有 locale_en-US.ini 和 locale_zh-CN.ini 两个本地化文件。 本地化文件的文件名和后缀是随意的&#xff0c;不…

vector迭代器的失效

1.vector的底层 vector的底层就是由三个指针构成的 iterator _start 这个指针指向vector数据起始位置。 iterator _finish这个指针指向vector数据的结束位置。 iterator _end_of_shorage这个指针指向vector容量的位置。 2.迭代器失效的种类 2.1扩容引发的迭代器失效 例&…

【GitHub项目推荐--微软开源的可视化工具】【转载】

说到数据可视化&#xff0c;大家都很熟悉了&#xff0c;设计师、数据分析师、数据科学家等&#xff0c;都需要用各种方式各种途径做着数据可视化的工作.....当然许多程序员在工作中有时也需要用到一些数据可视化工具&#xff0c;如果工具用得好&#xff0c;就可以把原本枯燥凌乱…

智能驾驶新浪潮:SSD与UFS存储技术如何破浪前行?- SSD篇

随着汽车行业的不断发展&#xff0c;对存储的需求也在不断的变化中。早期阶段的汽车对存储的需求主要是收音机、播放器、导航仪等&#xff0c;有些还可以支持光盘和U盘的外接播放。中期阶段&#xff0c;也是当前主流的燃油车行车记录、多媒体、车联网的需求&#xff0c;对存储性…

Jmeter 性能 —— 压测常遇问题+解决!

1、测试过程中CPU过高 用vmstat实时监控cpu使用情况。很小的压力AP cpu却到了80%多&#xff0c;指标是不能超过60%。vmstat 2 (每二秒显示一次系统内存的统计信息) 分析是use cpu过高还是sys cpu过高&#xff0c;常见的是use cpu使用过高。如果是sys cpu使用过高&#xff0c;先…

【内存管理】flink内存管理(一):内存管理概述:flink主动管理内存原理、flink内存模型

文章目录 一.flink为什么自己管理内存1. 处理大数据时JVM内存管理的问题2. flink主动管理内存逻辑2.1. Flink内存管理方面2.2. 序列化、反序列化说明 3. Flink主动管理内存的好处 二. Flink内存模型1. 堆内存2. 非堆内存2.1. 托管内存2.2.直接内存2.3. JVM特定内存 本节从整体使…

深入探索 Android 中的 Runtime

深入探索 Android 中的 Runtime 一、什么是 Runtime二、Android 中的 Runtime 类型2.1. Dalvik Runtime2.2. ART&#xff08;Android Runtime&#xff09; 三、Runtime 的作用和特点3.1. 应用程序执行环境3.2. 跨平台支持3.3. 性能优化3.4. 应用程序优化 四、与应用开发相关的重…

第十四章 MyBatis

第十四章 MyBatis 1.入门-课程介绍2.入门-快速入门程序3.配置SQL提示4.入门-JDBC5.入门-数据库连接池6.入门-lombok工具包介绍7.基础操作-环境准备8.基础操作-删除9.基础操作-删除&#xff08;预编译SQL&#xff09;10.基础操作-新增11.基础操作-新增&#xff08;主键返回&…

ctfshow命令执行(web29-web52)

目录 web29 web30 web31 web32 web33 web34 web35 web36 web37 web38 web39 web40 web41 web42 web43 web44 web45 web46 web47 web48 web49 web50 web51 web52 web29 <?php error_reporting(0); if(isset($_GET[c])){$c $_GET[c];if(!preg_match…

Leveraging Unlabeled Data for Crowd Counting by Learning to Rank

无标签人群技术&#xff0c;作者引入了一种排名。 利用的是一个图的人群数量一定小于等于包含这个图的图 生成排名数据集 作者提出了一种自监督任务&#xff0c;利用的是一个图的人群数量一定小于等于包含这个图的图 流程&#xff1a; 1.以图像中心为中心&#xff0c;划分一…

CentOS安装Flume

CentOS安装Flume 一、简介二、安装1、下载2、解压3、创建配置文件4、启动flume agent5、验证 一、简介 Flume is a distributed, reliable, and available service for efficiently collecting, aggregating, and moving large amounts of log data. It has a simple and flexi…