目录
父pom文件
pom文件
配置文件
MyResponseBodyAdvice
ResponseDto
MyBatisConfig
UsersController
UsersMapper
UserMapper.xml
结果
父pom文件
<?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>3.1.2</version>-->
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.chensir</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>springboot</description>
<properties>
<java.version>8</java.version>
<hutool.version>5.8.3</hutool.version>
<lombok.version>1.18.24</lombok.version>
<alibaba-sdk.version>2.0.0</alibaba-sdk.version>
</properties>
<packaging>pom</packaging>
<modules>
<module>servlet</module>
<module>spring-interceptor</module>
<module>spring-aop</module>
<module>spring-united-reslut</module>
<module>spring-jdbc</module>
<module>spring-mybatis</module>
</modules>
<dependencyManagement>
<dependencies>
<!--钉钉机器人消息-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibaba-dingtalk-service-sdk</artifactId>
<version>${alibaba-sdk.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!--父pom中不要加此依赖,否则依赖clean会报错,原因是父pom中并没指定版本-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-web</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
pom文件
<?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.chensir</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>spring-mybatis</artifactId>
<dependencies>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</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>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</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>
<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-test</artifactId>
<version>2.1.4</version>
<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>
配置文件
spring.datasource.url=jdbc:mysql://localhost/db1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
MyResponseBodyAdvice
package com.chensir.advice;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletRequest;
// 拦截范围为 com.chensir.controller包下内容
@RestControllerAdvice(basePackages = {"com.chensir.controller"})
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
// 是否开启拦截 true开启 false不开启
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
// 此处应该改为true,否则除了异常外 走到此处为false后就直接返回,也不再继续往下走了!
return true;
}
// 如果接口返回异常就在此处拦截 进行封装;value = Exception.class 对所有的异常均拦截!
@ExceptionHandler(value = Exception.class)
public Object defaultErrorHandler(HttpServletRequest req, Exception ex){
ResponseDto<Object> responseDto = new ResponseDto<>();
responseDto.setCode(501);
responseDto.setMessage(ex.getMessage());
return responseDto;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
// 有的接口再返回时会自己封装code,message,data。如果body是ResponseDto类型的实例,那么就直接返回body
// if(body instanceof ResponseDto){
// return body;
// }
ResponseDto<Object> responseDto = new ResponseDto<>();
// 先用hutool定义为null
String message = StrUtil.EMPTY;
responseDto.setCode(0);
responseDto.setMessage(message);
if (body instanceof Page){
Page page = (Page) body;
int pages = page.getPages();//总页数
long total = page.getTotal();//总条数
Dict dict = Dict.create()
.set("total",total)
.set("pages",pages)
.set("item",body);
responseDto.setData(dict);
}else {
responseDto.setData(body);
}
// 如果是string类型就用json封装一下;
if (aClass == StringHttpMessageConverter.class) {
return JSONUtil.toJsonStr(responseDto);
} else {
return responseDto;
}
}
}
ResponseDto<T>
package com.chensir.advice;
import lombok.Data;
import java.io.Serializable;
// 泛型
@Data
public class ResponseDto<T> implements Serializable {
// 返回码(内部拟定)
private int code;
// 返回信息
private String message;
private T data;
}
MyBatisConfig
package com.chensir.config;
import com.github.pagehelper.PageInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Configuration
@Slf4j
public class MyBatisConfig {
@Autowired
private ConfigurationCustomizer configurationCustomizer;
/**
* 自己注册SqlSessionFactory 目的是增强功能,添加分页插件
* @param ds 代表数据源
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
// 设置数据源
factoryBean.setDataSource(ds);
// 把分页插件设置到SqlSessionFactory插件库
factoryBean.setPlugins(new PageInterceptor());
// 配置mapper.xml地址
factoryBean.setMapperLocations(resolveMapperLocations());
//驼峰映射注册到SqlSessionFactory中
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configurationCustomizer.customize(configuration);
factoryBean.setConfiguration(configuration);
// 返回具体实例对象
SqlSessionFactory bean = factoryBean.getObject();
return bean;
}
/**
* 开启驼峰映射
* @return
*/
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
/**
* 查找 xxxMapper.xml
* @return
*/
public Resource[] resolveMapperLocations() {
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
List<String> mapperLocations = new ArrayList<>();
mapperLocations.add("classpath*:mapper/*Mapper.xml");
// mapperLocations.add("classpath*:com/meiwei/ping/dao/**/*Mapper.xml");
List<Resource> resources = new ArrayList();
if (!CollectionUtils.isEmpty(mapperLocations)) {
for (String mapperLocation : mapperLocations) {
try {
Resource[] mappers = resourceResolver.getResources(mapperLocation);
resources.addAll(Arrays.asList(mappers));
} catch (IOException e) {
log.error("Get myBatis resources happened exception", e);
}
}
}
return resources.toArray(new Resource[resources.size()]);
}
}
UsersController
package com.chensir.controller;
import com.chensir.entity.Users;
import com.chensir.service.UsersService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UsersController {
@Resource
private UsersService usersService;
@GetMapping("/demo1")
public List selectUsersList(Integer pageNum,Integer pageSize) {
// 启用分页,查询第一页,每页3条
PageHelper.startPage(pageNum,pageSize);
//-------------PageInfo方式---------------
// PageInfo<Users> usersPageInfo = new PageInfo<>(usersService.selectUsersList());
// return usersPageInfo;
//-------------PageInfo方式---------------
//-------------Page方式---------------
// List<Users> users = usersService.selectUsersList();
// Page page = (Page) users;
// int pages = page.getPages();
// long total = page.getTotal();
//
//
// Map<String,Object> pageMap = new HashMap<>();
// pageMap.put("pages",pages);
// pageMap.put("total",total);
// pageMap.put("items",users);
// return pageMap;
//-------------Page方式---------------
//-----------使用ResponseBodyAdvice------------
List<Users> users = usersService.selectUsersList();
return users;
//-----------使用ResponseBodyAdvice------------
}
@GetMapping("/demo2")
public Users selectUsers(){
Users users = usersService.selectUsers();
return users;
}
@GetMapping("/demo3")
public Map selectUsersToMap(){
return usersService.selectUsersToMap();
}
}
UsersMapper
@Mapper
public interface UsersMapper {
List<Users> selectUsersList();
Users selectUsers();
Map<String,Object> selectUsersToMap();
}
UserMapper.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.chensir.mapper.UsersMapper">
<select id="selectUsersList" resultType="com.chensir.entity.Users">
select * from users
</select>
<select id="selectUsers" resultType="com.chensir.entity.Users">
select * from users where id = 1
</select>
<select id="selectUsersToMap" resultType="java.util.Map">
select * from users where id = 1
</select>
</mapper>
结果
{
"code": 0,
"message": "",
"data": {
"total": 5,
"pages": 2,
"item": [
{
"id": 1,
"name": "chjnzkcn",
"age": 18,
"sex": "男",
"tel": "123",
"createTime": "2023-05-11",
"updateTime": "2023-05-11"
},
{
"id": 2,
"name": "czvfzsvdv",
"age": 20,
"sex": "男",
"tel": "2315",
"createTime": "2023-05-11",
"updateTime": "2023-05-11"
},
{
"id": 3,
"name": "sczvszv",
"age": 18,
"sex": "女",
"tel": "2112321",
"createTime": "2023-05-11",
"updateTime": "2023-05-11"
}
]
}
}