https://github.com/zq2599/blog_demos
内容:所有原创文章分类汇总及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;
名称 | 链接 | 备注 |
---|---|---|
项目主页 | https://github.com/zq2599/blog_demos | 该项目在GitHub上的主页 |
git仓库地址(https) | https://github.com/zq2599/blog_demos.git | 该项目源码的仓库地址,https协议 |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |
3. mybatis是个父工程,里面有数个子工程,本篇的源码在relatedoperation子工程中,如下图红框所示:
5. 建表和添加数据的语句如下:
use mybatis;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`age` int(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `log`;
CREATE TABLE `log` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`user_id` int(32),
`action` varchar(255) NOT NULL,
`create_time` datetime not null,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO mybatis.user (id, name, age) VALUES (3, ‘tom‘, 11);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (3, 3, ‘read book‘, ‘2020-08-07 08:18:16‘);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (4, 3, ‘go to the cinema‘, ‘2020-09-02 20:00:00‘);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (5, 3, ‘have a meal‘, ‘2020-10-05 12:03:36‘);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (6, 3, ‘have a sleep‘, ‘2020-10-06 13:00:12‘);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (7, 3, ‘write‘, ‘2020-10-08 09:21:11‘);
<?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>com.bolingcavalry</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>relatedoperation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>relatedoperation</name>
<description>Demo project for Mybatis related operation in Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<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>
</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>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
server:
port: 8080
spring:
#1.JDBC数据源
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.50.43:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
#2.连接池配置
druid:
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
# 配置一个连接在池中最大生存的时间,单位是毫秒
max-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM user
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,‘wall‘用于防火墙
filters: stat,wall,slf4j
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
#设置不统计哪些URL
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
#设置监控页面的登录名和密码
login-username: admin
login-password: admin
allow: 127.0.0.1
#deny: 192.168.1.100
# mybatis配置
mybatis:
# 配置文件所在位置
config-location: classpath:mybatis-config.xml
# 映射文件所在位置
mapper-locations: classpath:mappers/*Mapper.xml
# 日志配置
logging:
level:
root: INFO
com:
bolingcavalry:
relatedoperation:
mapper: debug
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<!-- 映射文件中的类不用写全路径了-->
<package name="com.bolingcavalry.relatedoperation.entity"/>
</typeAliases>
</configuration>
package com.bolingcavalry.relatedoperation;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DruidConfig {
private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.druid.initial-size}")
private int initialSize;
@Value("${spring.datasource.druid.max-active}")
private int maxActive;
@Value("${spring.datasource.druid.min-idle}")
private int minIdle;
@Value("${spring.datasource.druid.max-wait}")
private int maxWait;
@Value("${spring.datasource.druid.pool-prepared-statements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.max-evictable-idle-time-millis}")
private int maxEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.validation-query}")
private String validationQuery;
@Value("${spring.datasource.druid.test-while-idle}")
private boolean testWhileIdle;
@Value("${spring.datasource.druid.test-on-borrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.druid.test-on-return}")
private boolean testOnReturn;
@Value("${spring.datasource.druid.filters}")
private String filters;
@Value("{spring.datasource.druid.connection-properties}")
private String connectionProperties;
/**
* Druid 连接池配置
*/
@Bean
public DruidDataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (Exception e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
package com.bolingcavalry.relatedoperation;
import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.tags(new Tag("UserController", "用户服务"), new Tag("LogController", "日志服务"))
.select()
// 当前包路径
.apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.relatedoperation.controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("MyBatis CURD操作")
//创建人
.contact(new Contact("程序员欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
package com.bolingcavalry.relatedoperation;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.bolingcavalry.relatedoperation.mapper")
public class RelatedOperationApplication {
public static void main(String[] args) {
SpringApplication.run(RelatedOperationApplication.class, args);
}
}
package com.bolingcavalry.relatedoperation.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@ApiModel(description = "用户实体类")
public class User {
@ApiModelProperty(value = "用户ID")
private Integer id;
@ApiModelProperty(value = "用户名", required = true)
private String name;
@ApiModelProperty(value = "用户地址", required = false)
private Integer age;
}
package com.bolingcavalry.relatedoperation.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.sql.Date;
@Data
@NoArgsConstructor
@ApiModel(description = "日志实体类")
public class Log {
@ApiModelProperty(value = "日志ID")
private Integer id;
@ApiModelProperty(value = "用户ID")
private Integer userId;
@ApiModelProperty(value = "日志内容")
private String action;
@ApiModelProperty(value = "创建时间")
private Date createTime;
}
package com.bolingcavalry.relatedoperation.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@ApiModel(description = "日志实体类(含用户表的字段)")
public class LogExtend extends Log {
@ApiModelProperty(value = "用户名")
private String userName;
}
<?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.bolingcavalry.relatedoperation.mapper.LogMapper">
<!--联表查询,返回log对象,该对象有个userName字段,值是user表的user_name字段-->
<select id="oneObjectSel" parameterType="int" resultMap="logExtendResultMap">
select l.id as id,
l.user_id as user_id,
l.action as action,
l.create_time as create_time,
u.name as user_name
from log as l
left join user as u
on l.user_id = u.id
where l.id = #{id}
</select>
<resultMap id="logExtendResultMap" type="logExtend">
<id property="id" column="id"/>
<result column="user_id" jdbcType="INTEGER" property="userId"/>
<result column="action" jdbcType="VARCHAR" property="action"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<result column="user_name" jdbcType="VARCHAR" property="userName"/>
</resultMap>
</mapper>
package com.bolingcavalry.relatedoperation.mapper;
import com.bolingcavalry.relatedoperation.entity.LogAssociateUser;
import com.bolingcavalry.relatedoperation.entity.LogExtend;
import org.springframework.stereotype.Repository;
@Repository
public interface LogMapper {
LogExtend oneObjectSel(int id);
}
package com.bolingcavalry.relatedoperation.service;
import com.bolingcavalry.relatedoperation.entity.LogAssociateUser;
import com.bolingcavalry.relatedoperation.entity.LogExtend;
import com.bolingcavalry.relatedoperation.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LogService {
@Autowired
LogMapper logMapper;
public LogExtend oneObjectSel(int id){
return logMapper.oneObjectSel(id);
}
}
@RestController
@RequestMapping("/log")
@Api(tags = {"LogController"})
public class LogController {
@Autowired
private LogService logService;
@ApiOperation(value = "根据ID查找日志记录,带userName字段,该字段通过联表查询实现", notes="根据ID查找日志记录,带userName字段,该字段通过联表查询实现")
@ApiImplicitParam(name = "id", value = "日志ID", paramType = "path", required = true, dataType = "Integer")
@RequestMapping(value = "/aggregate/{id}", method = RequestMethod.GET)
public LogExtend oneObjectSel(@PathVariable int id){
return logService.oneObjectSel(id);
}
package com.bolingcavalry.relatedoperation.controller;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@DisplayName("Web接口的单元测试")
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Slf4j
public class ControllerTest {
/**
* 查询方式:联表
*/
final static String SEARCH_TYPE_LEFT_JOIN = "leftjoin";
/**
* 查询方式:嵌套
*/
final static String SEARCH_TYPE_NESTED = "nested";
final static int TEST_USER_ID = 3;
final static String TEST_USER_NAME = "tom";
@Autowired MockMvc mvc;
@Nested
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisplayName("用户服务")
class User {
}
@Nested
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisplayName("日志服务")
class Log {
final static int TEST_LOG_ID = 5;
@Test
@DisplayName("通过日志ID获取日志信息,带userName字段,该字段通过联表查询实现")
@Order(1)
void oneObjectSel() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/log/aggregate/" + TEST_LOG_ID)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(TEST_LOG_ID))
.andExpect(jsonPath("$.userName").value(TEST_USER_NAME))
.andDo(print());
}
}
}
@Data
@NoArgsConstructor
@ApiModel(description = "日志实体类")
public class LogAssociateUser {
@ApiModelProperty(value = "日志ID")
private Integer id;
@ApiModelProperty(value = "用户对象")
private User user;
@ApiModelProperty(value = "日志内容")
private String action;
@ApiModelProperty(value = "创建时间")
private Date createTime;
}
所谓一对一,就是一个对象关联了另一个对象,例如一条log记录中,带有对应的user信息;
@Data
@NoArgsConstructor
@ApiModel(description = "日志实体类")
public class LogAssociateUser {
@ApiModelProperty(value = "日志ID")
private Integer id;
@ApiModelProperty(value = "用户对象")
private User user;
@ApiModelProperty(value = "日志内容")
private String action;
@ApiModelProperty(value = "创建时间")
private Date createTime;
}
<!--联表查询,返回log对象,它的成员变量中有user对象-->
<select id="leftJoinSel" parameterType="int" resultMap="leftJoinResultMap">
select l.id as log_id,
l.action as log_action,
l.create_time as log_create_time,
u.id as user_id,
u.name as user_name,
u.age as user_age
from log as l
left join user as u
on l.user_id = u.id
where l.id = #{id}
</select>
<resultMap id="leftJoinResultMap" type="LogAssociateUser">
<id property="id" column="log_id"/>
<result property="action" column="log_action" jdbcType="VARCHAR"/>
<result property="createTime" column="log_create_time" jdbcType="TIMESTAMP" />
<association property="user" javaType="User">
<id property="id" column="user_id"/>
<result property="name" column="user_name"/>
<result property="age" column="user_age"/>
</association>
</resultMap>
@ApiOperation(value = "根据ID查找日志记录,带用户对象,联表查询实现", notes="根据ID查找日志记录,带用户对象,联表查询实现")
@ApiImplicitParam(name = "id", value = "日志ID", paramType = "path", required = true, dataType = "Integer")
@RequestMapping(value = "/leftjoin/{id}", method = RequestMethod.GET)
public LogAssociateUser leftJoinSel(@PathVariable int id){
return logService.leftJoinSel(id);
}
/**
* 通过日志ID获取日志信息有两种方式:联表和嵌套查询,
* 从客户端来看,仅一部分path不同,因此将请求和检查封装到一个通用方法中,
* 调用方法只需要指定不同的那一段path
* @param subPath
* @throws Exception
*/
private void queryAndCheck(String subPath) throws Exception {
String queryPath = "/log/" + subPath + "/" + TEST_LOG_ID;
log.info("query path [{}]", queryPath);
mvc.perform(MockMvcRequestBuilders.get(queryPath)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(TEST_LOG_ID))
.andExpect(jsonPath("$.user.id").value(TEST_USER_ID))
.andDo(print());
}
@Test
@DisplayName("通过日志ID获取日志信息(关联了用户),联表查询")
@Order(2)
void leftJoinSel() throws Exception {
queryAndCheck(SEARCH_TYPE_LEFT_JOIN);
}
<!--嵌套-->
<select id="nestedSel" parameterType="int" resultMap="nestedResultMap">
select
l.id as log_id,
l.user_id as log_user_id,
l.action as log_action,
l.create_time as log_create_time
from mybatis.log as l
where l.id = #{id}
</select>
<!-- association节点的select属性会触发嵌套查询-->
<resultMap id="nestedResultMap" type="LogAssociateUser">
<!-- column属性中的log_id,来自前面查询时的"l.id as log_id" -->
<id property="id" column="log_id"/>
<!-- column属性中的log_action,来自前面查询时的"l.action as log_action" -->
<result property="action" column="log_action" jdbcType="VARCHAR"/>
<!-- column属性中的log_create_time,来自前面查询时的"l.create_time as log_create_time" -->
<result property="createTime" column="log_create_time" jdbcType="TIMESTAMP" />
<!-- select属性,表示这里要执行嵌套查询,将log_user_id传给嵌套的查询 -->
<association property="user" column="log_user_id" select="selectUserByUserId"></association>
</resultMap>
<select id="selectUserByUserId" parameterType="int" resultType="User">
select
u.id,
u.name,
u.age
from mybatis.user as u
where u.id = #{log_user_id}
</select>
@ApiOperation(value = "根据ID查找日志记录,带用户对象,嵌套查询实现", notes="根据ID查找日志记录,带用户对象,嵌套查询实现")
@ApiImplicitParam(name = "id", value = "日志ID", paramType = "path", required = true, dataType = "Integer")
@RequestMapping(value = "/nested/{id}", method = RequestMethod.GET)
public LogAssociateUser nestedSel(@PathVariable int id){
return logService.nestedSel(id);
}
@Test
@DisplayName("通过日志ID获取日志信息(关联了用户),嵌套查询")
@Order(3)
void nestedSel() throws Exception {
queryAndCheck(SEARCH_TYPE_NESTED);
}
8. 最后是对比联表和嵌套查询的差异,先看联表查询的MyBatis日志,如下图红框所示,只有一次sql查询:
9. 再看嵌套查询的日志,如下图,红框是第一次查询,结果中的userid作为绿框中的第二次查询的条件:
微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...
https://github.com/zq2599/blog_demos
原文:https://www.cnblogs.com/bolingcavalry/p/14306122.html