一、springboot整合Mybatis
1.准备工具:IDEA
浏览器直接搜索IDEA进入官网,点击Download,进入如下页面

第一个是旗舰版,第二个是社区版,一个要钱一个免费,但是第一个可以用其他方法进行使用,本文用的是旗舰版2020。
下载完后进行安装,基本就是一路next,然后完成。

首次打开旗舰版 IDEA 时,会让你激活,这里有 3 种选择:
- 利用你的 JetBrains 账号登录激活;
- 利用你的 IDEA 激活码激活;
- 最后则是许可证服务器地址激活;
这里选择Evaluate for free使用三十天,进去之后打开设置,找到插件。

?第一个是将IDEA换成中文版,第二个则可以让你的旗舰版idea反复使用三十天

?
?进行以上步骤,选择“是”将idea重启,则试用日期又会变成30天,每个月只需要刷一两次就能一直使用了。
2.创建项目

?可以使用默认,就是有点慢,这里使用的是阿里云镜像的地址,然后下一步。
?
?这里只要设置框内内容,继续下一步。

选择项目需要的依赖,第一个是springboot的基本依赖,下面两个是mybatis的依赖和驱动依赖 ,继续下一步。

选择项目名称和存放路径,完成项目创建。
?1是我们的启动类。2是我们的配置文件。3是我们管理依赖的地方,可以通过右边的maven进行依赖引用情况。
3.引用逆向工程依赖
<!-- mybatis自动生成代码 的插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置文件路径。启动插件时,插件会根据这里配置的路径去找到generatorConfig.xml配置文件,
根据配置文件里的配置,去自动生成Mapper接口(可以理解为Dao层)、实体类、Mapper.xml文件
-->
<configurationFile>src/main/resources/GeneratorConfig.xml</configurationFile>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
总体如下图
<?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.test</groupId>
<artifactId>project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.test.project.ProjectApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- mybatis自动生成代码 的插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置文件路径。启动插件时,插件会根据这里配置的路径去找到generatorConfig.xml配置文件,
根据配置文件里的配置,去自动生成Mapper接口(可以理解为Dao层)、实体类、Mapper.xml文件
-->
<configurationFile>src/main/resources/GeneratorConfig.xml</configurationFile>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.创建数据库(mysql)
使用Navicat Premium 15工具进行mysql的管理
a.新建数据库
CREATE DATABASE `test_project` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';
?b.新建表(学生表,老师表)
创建学生表
CREATE TABLE `test_project`.`student` (
`student_id` varchar(255) NOT NULL COMMENT '学生ID',
`student_name` varchar(255) NOT NULL COMMENT '学生姓名',
`student_age` varchar(255) NOT NULL COMMENT '学生年龄',
`student_sex` varchar(255) NOT NULL COMMENT '学生性别',
PRIMARY KEY (`student_id`)
);
插入三条数据
INSERT INTO `test_project`.`student`(`student_id`, `student_name`, `student_age`, `student_sex`) VALUES ('12345601', '张三', '15', '男');
INSERT INTO `test_project`.`student`(`student_id`, `student_name`, `student_age`, `student_sex`) VALUES ('12345602', '李四', '18', '女');
INSERT INTO `test_project`.`student`(`student_id`, `student_name`, `student_age`, `student_sex`) VALUES ('12345603', '王五', '17', '男');
创建老师表
CREATE TABLE `test_project`.`teacher` (
`teacher_id` varchar(255) NOT NULL COMMENT '老师Id',
`teacher_name` varchar(255) NOT NULL COMMENT '老师姓名',
`course` varchar(255) NOT NULL COMMENT '教学课程',
PRIMARY KEY (`teacher_id`)
);
插入两条数据
INSERT INTO `test_project`.`teacher`(`teacher_id`, `teacher_name`, `course`) VALUES ('111111', '赵老师', '语文');
INSERT INTO `test_project`.`teacher`(`teacher_id`, `teacher_name`, `course`) VALUES ('222222', '向老师', '数学');
创建关联表
CREATE TABLE `test_project`.`associate` (
`associate_id` int NOT NULL AUTO_INCREMENT COMMENT '关联ID',
`teacher_id` varchar(255) NOT NULL COMMENT '老师ID',
`student_id` varchar(255) NOT NULL COMMENT '学生ID',
PRIMARY KEY (`associate_id`)
);
添加关联数据
INSERT INTO `test_project`.`associate`(`associate_id`, `teacher_id`, `student_id`) VALUES (1, '111111', '12345601');
INSERT INTO `test_project`.`associate`(`associate_id`, `teacher_id`, `student_id`) VALUES (2, '111111', '12345603');
INSERT INTO `test_project`.`associate`(`associate_id`, `teacher_id`, `student_id`) VALUES (3, '222222', '12345601');
INSERT INTO `test_project`.`associate`(`associate_id`, `teacher_id`, `student_id`) VALUES (4, '222222', '12345602');
表结构如下

5.配置相关文件
a.新建文件GeneratorConfig.xml

b.配置GeneratorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1.0.dtd">
<generatorConfiguration>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包 -->
<!-- 因为已经在pom.xml添加逆向工程插件时添加了驱动依赖,所以省略这一步-->
<!-- <classPathEntry location="C:\Users\lenovo\Desktop\Software_project\java\mysql-connector-java-8.0.28/mysql-connector-java-8.0.28.jar"/>-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 实体类生成序列化属性-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 实体类重写HashCode()和equals()-->
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<!-- 实体类重写toString() -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<commentGenerator>
<!-- 是否去除自动生成的注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 生成注释是否带时间戳-->
<property name="suppressDate" value="true"/>
<!-- 生成的Java文件的编码格式 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- 数据库注释支持 -->
<property name="addRemarkComments" value="true"/>
<!-- 时间格式设置 -->
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
<!-- 格式化java代码-->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码-->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
</commentGenerator>
<!-- 数据库连接驱动类,URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test_project?serverTimezone=GMT&useSSL=false"
userId="root"
password="root">
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- java类型处理器:处理DB中的类型到Java中的类型 -->
<javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
<!-- 是否有效识别DB中的BigDecimal类型 -->
<property name="forceBigDecimals" value="true"/>
</javaTypeResolver>
<!-- 生成Domain模型:包名(targetPackage)、位置(targetProject) -->
<javaModelGenerator targetPackage="com.test.project.entity" targetProject="C:\Users\lenovo\Desktop\project\src\main\java">
<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
<property name="enableSubPackages" value="true"/>
<!-- 设置是否在getter方法中,对String类型字段调用trim()方法-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成xml映射文件:包名(targetPackage)、位置(targetProject) -->
<sqlMapGenerator targetPackage="mapper" targetProject="C:\Users\lenovo\Desktop\project\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO接口:包名(targetPackage)、位置(targetProject) -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.test.project.dao"
targetProject="C:\Users\lenovo\Desktop\project\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表:tableName - 数据库中的表名或视图名,domainObjectName - 实体类名 -->
<table tableName="student" domainObjectName="Student"></table>
<table tableName="teacher" domainObjectName="Teacher">
<!-- 若数据库中某个属性类型为text或类似类型,可能会发生无法生成这个属性,此时可以在这里指定转换类型为VARCHAR-->
<!-- <columnOverride column="teacher_name" jdbcType="VARCHAR" />-->
</table>
</context>
</generatorConfiguration>
?c.配置application.properties文件
# 应用名称
spring.application.name=project
# 应用服务 WEB 访问端口
server.port=8080
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mapper/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.test.project.mybatis.entity
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/test_project?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=root
6.逆向生成文件

?如图依次打开,生成结果如下

?二、使用mybatis逆向工程实现数据的增、删、查、改
1.mapper接口中的方法
方法 | 功能说明 |
---|
int countByExample(UserExample example) thorws SQLException | 按条件计数 | int deleteByPrimaryKey(Integer id) thorws SQLException | 按主键删除 | int deleteByExample(UserExample example) thorws SQLException | 按条件删除 | String/Integer insert(User record) thorws SQLException | 插入数据(返回值为ID) | List selectByExample(UserExample example) thorws SQLException | 按条件查询 | User selectByPrimaryKey(Integer id) thorws SQLException | 按主键查询 | ListselectByExampleWithBLOGs(UserExample example) thorws SQLException | 按条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。 | int updateByPrimaryKey(User record) thorws SQLException | 按主键更新 | int updateByPrimaryKeySelective(User record) thorws SQLException | 按主键更新值不为null的字段 | int updateByExample(User record, UserExample example) thorws SQLException | 按条件更新 | int updateByExampleSelective(User record, UserExample example) thorws SQLException | 按条件更新值不为null的字段 |
2.example实例解析
mybatis的逆向工程中会生成实例及实例对应的example,example用于添加条件,相当where后面的部分: XxxExample example = new XxxExample(); XxxExample.criteria? criteria?= example.createCriteria();
方法 | 功能说明 |
---|
example.setOrderByClause(“字段名 ASC”); | 添加升序排列条件,DESC为降序 | example.setDistinct(false) | 去除重复,boolean型,true为选择不重复的记录。 | criteria.andXxxIsNull | 添加字段xxx为null的条件 | criteria.andXxxIsNotNull | 添加字段xxx不为null的条件 | criteria.andXxxEqualTo(value) | 添加xxx字段等于value条件 | criteria.andXxxNotEqualTo(value) | 添加xxx字段不等于value条件 | criteria.andXxxGreaterThan(value) | 添加xxx字段大于value条件 | criteria.andXxxGreaterThanOrEqualTo(value) | 添加xxx字段大于等于value条件 | criteria.andXxxLessThan(value) | 添加xxx字段小于value条件 | criteria.andXxxLessThanOrEqualTo(value) | 添加xxx字段小于等于value条件 | criteria.andXxxIn(List<?>) | 添加xxx字段值在List<?>条件 | criteria.andXxxNotIn(List<?>) | 添加xxx字段值不在List<?>条件 | criteria.andXxxLike(“%”+value+”%”) | 添加xxx字段值为value的模糊查询条件 | criteria.andXxxNotLike(“%”+value+”%”) | 添加xxx字段值不为value的模糊查询条件 | criteria.andXxxBetween(value1,value2) | 添加xxx字段值在value1和value2之间条件 | criteria.andXxxNotBetween(value1,value2) | 添加xxx字段值不在value1和value2之间条件 |
3.具体实现(以查询为例)
首先创建service层的包,然后创建查询接口,代码如下:
package com.test.project.service;
import com.test.project.entity.Student;
import java.util.List;
public interface SelectService {
//查询所有学生信息
List<Student> selectAllStudent();
//按主键查询某个学生信息
Student selectByStudentId(String stuId);
//按性别查询学生信息
List<Student> selectBySex(String sex);
}
然后创建实现类,创建时注意添加注解,代码如下:
package com.test.project.service.imp;
import com.test.project.dao.StudentMapper;
import com.test.project.entity.Student;
import com.test.project.entity.StudentExample;
import com.test.project.service.SelectService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Service
public class SelectServiceImp implements SelectService {
@Autowired
private StudentMapper studentMapper;
@Override
public List<Student> selectAllStudent() {
return studentMapper.selectByExample(new StudentExample());
}
@Override
public Student selectByStudentId(String stuId) {
return studentMapper.selectByPrimaryKey(stuId);
}
@Override
public List<Student> selectBySex(String sex) {
StudentExample studentExample = new StudentExample();
StudentExample.Criteria criteria = studentExample.createCriteria();
criteria.andStudentSexEqualTo(sex);
return studentMapper.selectByExample(studentExample);
}
}
在调用XxxMapper接口时,会报错,是因为还没有对Mapper接口进行映射,只需要在接口上面加上@Mapper注解就可以了,也可以直接在启动类上添加@MapperScan注解,并指定需要扫描的basePackages,代码如下
@MapperScan(basePackages = {"com.test.project.dao"})
此时依旧报红,是因为还没有将其指定为bean,只需要在接口上加入@Repository注解就行了。
最后在测试类中进行调用,代码如下:
package com.test.project;
import com.test.project.entity.Student;
import com.test.project.entity.Teacher;
import com.test.project.model.StudentWithTeacher;
import com.test.project.service.SelectService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class StudentTest {
@Autowired
private SelectService selectService;
@Test
public void selectStudent(){
// 查询所有学生信息
List<Student> studentList1 = selectService.selectAllStudent();
// 条件查询性别为男生的学生信息
List<Student> studentList2 = selectService.selectBySex("男");
// 查询学号为12345601的学生信息
Student student = selectService.selectByStudentId("12345601");
System.out.println("所有学生信息如下:");
for (Student stu1:studentList1) {
System.out.println(stu1.toString());
}
System.out.println("所有男学生信息如下:");
for (Student stu1:studentList2) {
System.out.println(stu1.toString());
}
System.out.println("学号为12345601的学生信息如下:");
System.out.println(student.toString());
}
}
结果如下:

此时项目结构如下图:

?三、联表查询
在实际运用时,我们会发现mybatis逆向工程只能用于单表操作,而不能进行联表操作,因此还需要自己手动进行一些改变,来满足功能需求。下面以多对多为例,实现学生表与教师表的联表查询。
1.实体类
修改原来的实体类或者新建一个实体类,存放需要查询的对象属性,如果数据库结构有变,重新进行逆向工程时,原来生成的文件需要删除,所以为了与原来逆向工程的文件分开来,这里选择新建实体类,代码如下:
package com.test.project.model;
import com.test.project.entity.Student;
import com.test.project.entity.Teacher;
import java.util.List;
import java.util.Objects;
public class StudentWithTeacher extends Student {
/*
* 一对多查询
* 一个学生对应多个老师
* */
private Student student;//学生类
private List<Teacher> teacherList;//每个学生类对应的老师列表
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public List<Teacher> getTeacherList() {
return teacherList;
}
public void setTeacherList(List<Teacher> teacherList) {
this.teacherList = teacherList;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
StudentWithTeacher that = (StudentWithTeacher) o;
return Objects.equals(student, that.student) && Objects.equals(teacherList, that.teacherList);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), student, teacherList);
}
@Override
public String toString() {
return "StudentWithTeacher{" +
"student=" + student +
", teacherList=" + teacherList +
'}';
}
}
?2.mapper接口
自定义一个mapper接口,可以放在原来的dao包下,也能重新创建一个包,不过记得加上@mapper和@Repository两个注解,这里是新建一个包,与上面同理。代码如下:
package com.test.project.personalMapper;
import com.test.project.entity.StudentExample;
import com.test.project.model.StudentWithTeacher;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface StudentWithTeacherMapper {
List<StudentWithTeacher> findStudentWithTeacher(StudentExample example);
}
3.mapper配置文件
创建Xxxmapper.xml配置文件,放在mpper文件下面,因为配置文件中已经规定了mpper文件的映射路径。在xml文件中编写sql的查询语句。代码如下:
<?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.test.project.personalMapper.StudentWithTeacherMapper">
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
and associate.teacher_id = teacher.teacher_id
and associate.student_id = student.student_id
</where>
</sql>
<select id="findStudentWithTeacher" parameterType="com.test.project.model.StudentWithTeacher" resultMap="StudentWithTeacherResult">
select
<if test="distinct">
distinct
</if>
student.*,teacher.*
from student,teacher,associate
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<resultMap id="StudentWithTeacherResult" type="com.test.project.model.StudentWithTeacher">
<id column="student_id" jdbcType="VARCHAR" property="student.studentId" />
<result column="student_name" jdbcType="VARCHAR" property="student.studentName" />
<result column="student_age" jdbcType="VARCHAR" property="student.studentAge" />
<result column="student_sex" jdbcType="VARCHAR" property="student.studentSex" />
<collection property="teacherList" column="teacher_id" ofType="com.test.project.entity.Teacher">
<id column="teacher_id" jdbcType="VARCHAR" property="teacherId" />
<result column="teacher_name" jdbcType="VARCHAR" property="teacherName" />
<result column="course" jdbcType="VARCHAR" property="course" />
</collection>
</resultMap>
</mapper>
4.编写service层代码
a.接口如下:
package com.test.project.service;
import com.test.project.entity.Student;
import com.test.project.model.StudentWithTeacher;
import java.util.List;
public interface SelectService {
//查询所有学生信息
List<Student> selectAllStudent();
//按主键查询某个学生信息
Student selectByStudentId(String stuId);
//按性别查询学生信息
List<Student> selectBySex(String sex);
//查询所有学生及其老师
List<StudentWithTeacher> selectStudentWithTeacherAll();
}
b.实现类如下:
package com.test.project.service.imp;
import com.test.project.dao.StudentMapper;
import com.test.project.entity.Student;
import com.test.project.entity.StudentExample;
import com.test.project.model.StudentWithTeacher;
import com.test.project.personalMapper.StudentWithTeacherMapper;
import com.test.project.service.SelectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SelectServiceImp implements SelectService {
@Autowired
private StudentMapper studentMapper;//单表查询的mapper接口
@Autowired
private StudentWithTeacherMapper studentWithTeacherMapper;//联表查询的mapper接口
@Override
public List<Student> selectAllStudent() {
return studentMapper.selectByExample(new StudentExample());
}
@Override
public Student selectByStudentId(String stuId) {
return studentMapper.selectByPrimaryKey(stuId);
}
@Override
public List<Student> selectBySex(String sex) {
StudentExample studentExample = new StudentExample();
StudentExample.Criteria criteria = studentExample.createCriteria();
criteria.andStudentSexEqualTo(sex);
return studentMapper.selectByExample(studentExample);
}
@Override
public List<StudentWithTeacher> selectStudentWithTeacherAll() {
return studentWithTeacherMapper.findStudentWithTeacher(new StudentExample());
}
}
5.编写测试类
@Test
public void selectStudentWithTeacher(){
List<StudentWithTeacher> studentList = selectService.selectStudentWithTeacherAll();
for (StudentWithTeacher stu:studentList) {
System.out.println(stu.getStudent().toString());
for (Teacher te:stu.getTeacherList()) {
System.out.println(te.toString());
}
}
}
此时,因为关联表中的两个关联属性与其他两个表的主键重名,若通过主键属性名进行查找时,会分不清是通过哪个表的属性名进行查找,所以需要修改XxxExample中的代码,具体如下:

?找到需要调用的方法,其中有三个值,一个是sql语句的属性名,一个是传进来的值和值的名字,只需要将第一值前面加上这个值得表名就行了,对其他方法也适用。
6.测试结果如下:

这样就实现了联表查询。
四、结论
Mybatis是一个支持普通SQL查询、存储及高级映射的持久框架,它几乎消除了JDBC的冗余代码,无须手动设置参数和对结果进行检索,使用简单的XML或注解进行配置和原理映射,将接口和Java的POJO映射成数据库中的记录,使java开发人员可以使用面向对象的编程思想来操作数据库。
在开发过程中,为了减少编写的代码量,使用mybatis逆向工程可以省略大部分代码的编写,如果想增加其他操作,只需要在其基础上添加新的mapper接口及映射就行了。
|