MyBatis初级实战之五:一对一关联查询,2024蚂蚁金服面试题及答案

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024b (备注Java)
img

正文

  1. 基本配置文件application.yml:

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

  1. 再准备名为application-test.yml的配置文件,这是执行单元测试时用到的,和application.yml的不同之处是spring.datasource.druid.web-stat-filter.enabled配置设置成false;

  2. mybatis的配置文件mybatis-config.xml如下:

  1. 数据源配置类DruidConfig.java:

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;

}

}

  1. swagger配置类:

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

}

}

  1. springboot引导类:

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

}

}

  1. 用户表的实体类:

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;

}

  1. 日志表的实体类:

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;

}

  • 以上就是本篇的准备代码,接下来在此基础上实现各种多表关联查询

最简单的联表

  • 先实战的是最普通的联表,如下图所示,查询结果是名为LogExtend的实体类,这个类有5个字段,其中四个来自日志表log,一个来自用户表user:

在这里插入图片描述

  • 下图是开发步骤:

在这里插入图片描述

  1. 实体类LogExtend的源码如下,可见和Log相比多了个userName字段:

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;

}

  1. 新建log表对应的映射文件LogMapper.xml,如下所示,里面是通过left join语法执行的简单的联表查询,以及查询结果对应的resultMap定义:
<?xml version="1.0" encoding="UTF-8"?>

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}

  1. 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);

}

  1. service层的代码在LogService.java文件中:

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

}

}

  1. controller层的代码在LogController.java文件中:

@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);

}

  1. 编写单元测试的代码ControllerTest.java,由于今天的测试涉及到user和log两个表,因此在测试类ControllerTest的内部准备了两个内部类,分别用于测试user和log表:

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

}

}

}

  1. 执行上述单元测试方法,结果如下图,红框中就是controller层返回的数据,可见已通过Mybatis成功取得LogExtend实例:

在这里插入图片描述

  • 下一站是一对一联表查询;

关于一对一关联的两种方式

  • 前面的查询有个特点:尽管查询了两个表,但结果都在同一实体类的不同字段,而更符合业务逻辑的关系应该是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 = “创建时间”)

最后

一次偶然,从朋友那里得到一份“java高分面试指南”,里面涵盖了25个分类的面试题以及详细的解析:JavaOOP、Java集合/泛型、Java中的IO与NIO、Java反射、Java序列化、Java注解、多线程&并发、JVM、Mysql、Redis、Memcached、MongoDB、Spring、Spring Boot、Spring Cloud、RabbitMQ、Dubbo 、MyBatis 、ZooKeeper 、数据结构、算法、Elasticsearch 、Kafka 、微服务、Linux。

这不,马上就要到招聘季了,很多朋友又开始准备“金三银四”的春招啦,那我想这份“java高分面试指南”应该起到不小的作用,所以今天想给大家分享一下。

image

请注意:关于这份“java高分面试指南”,每一个方向专题(25个)的题目这里几乎都会列举,在不看答案的情况下,大家可以自行测试一下水平 且由于篇幅原因,这边无法展示所有完整的答案解析

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

量,即如下形式:

@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 = “创建时间”)

最后

一次偶然,从朋友那里得到一份“java高分面试指南”,里面涵盖了25个分类的面试题以及详细的解析:JavaOOP、Java集合/泛型、Java中的IO与NIO、Java反射、Java序列化、Java注解、多线程&并发、JVM、Mysql、Redis、Memcached、MongoDB、Spring、Spring Boot、Spring Cloud、RabbitMQ、Dubbo 、MyBatis 、ZooKeeper 、数据结构、算法、Elasticsearch 、Kafka 、微服务、Linux。

这不,马上就要到招聘季了,很多朋友又开始准备“金三银四”的春招啦,那我想这份“java高分面试指南”应该起到不小的作用,所以今天想给大家分享一下。

[外链图片转存中…(img-hHsdc6FS-1713639775535)]

请注意:关于这份“java高分面试指南”,每一个方向专题(25个)的题目这里几乎都会列举,在不看答案的情况下,大家可以自行测试一下水平 且由于篇幅原因,这边无法展示所有完整的答案解析

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-r4WAtes1-1713639775535)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值