mybatis级联查询之一对一
参考网址:
https://blog.csdn.net/abc997995674/article/details/80873053?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161391222616780262548477%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=161391222616780262548477&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-80873053.first_rank_v2_pc_rank_v29&utm_term=mybatis%E4%B8%80%E5%AF%B9%E4%B8%80
1.新建springboot工程,导入相关依赖和配置
pom.xml
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.shaoming</groupId>
<artifactId>springboot-test-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-test-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
<!--<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--引入thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
说明:
mybatis和mybatis-plus配置基本一致
如果对mybatis进行配置,把配置前缀mybatis-plus改为mybatis
server.port=8080
spring.application.name=springboot-demo
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#定义mybatis别名包
mybatis-plus.type-aliases-package=com.shaoming.model.entity
#设置mapper.xml的文件位置
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
#开启驼峰
mybatis-plus.configuration.map-underscore-to-camel-case=true
#配置mybatis级联查询懒加载
mybatis-plus.configuration.aggressive-lazy-loading=false
mybatis-plus.configuration.lazy-loading-enabled=true
#打印日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置日志
#logging.level.com.shaoming.mapper=debug
2.导入表写对应实体类
建表建库脚本
/*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.5.5-10.3.7-MariaDB : Database - mybatis_test
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis_test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mybatis_test`;
/*Table structure for table `tbl_department` */
DROP TABLE IF EXISTS `tbl_department`;
CREATE TABLE `tbl_department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`department_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*Data for the table `tbl_department` */
LOCK TABLES `tbl_department` WRITE;
insert into `tbl_department`(`id`,`department_name`) values (1,'dept1'),(2,'dept2');
UNLOCK TABLES;
/*Table structure for table `tbl_employee` */
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`dept_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*Data for the table `tbl_employee` */
LOCK TABLES `tbl_employee` WRITE;
insert into `tbl_employee`(`id`,`last_name`,`gender`,`email`,`dept_id`) values (1,'name1','男','[email protected]',1),(2,'name2','男','[email protected]',2);
UNLOCK TABLES;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
Employee
package com.shaoming.model.entity;
public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
private Department dept;
//...省略get/set/toString方法
}
Department
package com.shaoming.model.entity;
public class Department {
private Integer id;
private String departmentName;
//...省略get/set/toString方法
}
3.写Mapper接口和Mapper.xml
EmployeeMapper
package com.shaoming.mapper;
import com.shaoming.model.entity.Employee;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface EmployeeMapper {
Employee getEmpAndDeptById(Integer id);
Employee getEmpAndDeptByStep(Integer id);
}
DepartmentMapper
package com.shaoming.mapper;
import com.shaoming.model.entity.Department;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DepartmentMapper {
Department getDeptById(Integer id);
}
EmployeeMapper.xml
<?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.shaoming.mapper.EmployeeMapper">
<resultMap type="com.shaoming.model.entity.Employee" id="myEmp">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!-- 关联对象 -->
<association property="dept" javaType="com.shaoming.model.entity.Department">
<!-- 关联条件Employee的dept_id对应着Department的id -->
<id column="dept_id" property="id"/>
<result column="department_name" property="departmentName"/>
</association>
</resultMap>
<select id="getEmpAndDeptById" resultMap="myEmp">
select e.id,e.last_name,e.gender,e.email,e.dept_id,d.id,d.department_name
from tbl_employee e,tbl_department d
where e.dept_id = d.id and e.id=#{id}
</select>
<resultMap type="com.shaoming.model.entity.Employee" id="myEmpByStep">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!-- 使用select属性指定第二步调用的方法,并通过column指定传递的参数值,这个值是第一步的查询的数据 -->
<association property="dept"
select="com.shaoming.mapper.DepartmentMapper.getDeptById"
column="dept_id">
</association>
</resultMap>
<!-- 第一步值只查询tbl_employee表 -->
<select id="getEmpAndDeptByStep" resultMap="myEmpByStep">
select id,last_name,gender,email,dept_id
from tbl_employee
where id = #{id}
</select>
</mapper>
DepartmentMapper.xml
<?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.shaoming.mapper.DepartmentMapper">
<select id="getDeptById" resultType="com.shaoming.model.entity.Department">
select * from tbl_department
where id = #{id}
</select>
</mapper>
4.测试懒加载
测试1
package com.shaoming;
import com.shaoming.mapper.DepartmentMapper;
import com.shaoming.mapper.EmployeeMapper;
import com.shaoming.model.entity.Department;
import com.shaoming.model.entity.Employee;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @Auther: shaoming
* @Date: 2021/1/11 15:38
* @Description:
*/
@SpringBootTest
public class DaoTest {
@Autowired
private EmployeeMapper employeeMapper;
@Test
public void test31() {
Employee employ = employeeMapper.getEmpAndDeptByStep(1);
System.out.println("employ的name为:"+employ.getLastName());
// System.out.println(employ);
}
}
打印了一条sql语句
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e4c2d5] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@2127814459 wrapping com.mysql.cj.jdbc.ConnectionImpl@465b38e6] will not be managed by Spring
> Preparing: select id,last_name,gender,email,dept_id from tbl_employee where id = ?
> Parameters: 1(Integer)
< Columns: id, last_name, gender, email, dept_id
< Row: 1, name1, 男, [email protected], 1
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e4c2d5]
employ的name为:name1
测试2
@Test
public void test31() {
Employee employ = employeeMapper.getEmpAndDeptByStep(1);
// System.out.println("employ的name为:"+employ.getLastName());
System.out.println(employ);
}
打印两条sql
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e4c2d5] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@2127814459 wrapping com.mysql.cj.jdbc.ConnectionImpl@465b38e6] will not be managed by Spring
> Preparing: select id,last_name,gender,email,dept_id from tbl_employee where id = ?
> Parameters: 1(Integer)
< Columns: id, last_name, gender, email, dept_id
< Row: 1, name1, 男, [email protected], 1
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e4c2d5]
JDBC Connection [HikariProxyConnection@19423 wrapping com.mysql.cj.jdbc.ConnectionImpl@465b38e6] will not be managed by Spring
> Preparing: select * from tbl_department where id = ?
> Parameters: 1(Integer)
< Columns: id, department_name
< Row: 1, dept1
<== Total: 1
Employee [id=1, lastName=name1, gender=男, [email protected], dept=Department [id=1, departmentName=dept1]]
5.mybatis懒加载
springboot项目配置懒加载
mybatis-plus配置
application.properties
#配置mybatis级联查询懒加载
mybatis-plus.configuration.aggressive-lazy-loading=false
mybatis-plus.configuration.lazy-loading-enabled=true
mybaits配置
application.properties
#配置mybatis级联查询懒加载
mybatis.configuration.aggressive-lazy-loading=false
mybatis.configuration.lazy-loading-enabled=true
ssm项目配置懒加载
在conf文件中配置settings:
<settings>
<!-- 设置驼峰属性 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 配置懒加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 其他配置略 -->
</settings>