创建SpringBoot项目的过程此处忽略。
集成MySQL实现最简单的增删改查功能。
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.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>MyMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MyMybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- 引入knife4j,增强swagger页面-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</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>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
User:
@Data
public class User {
private Integer userId;
private String userName;
@Override
public String toString() {
return "User{" +
"user_id=" + userId +
", user_name='" + userName + '\'' +
'}';
}
}
MybatisController:
package com.springboot.MyMybatis.controller;
import com.springboot.MyMybatis.entity.User;
import com.springboot.MyMybatis.service.MybatisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/mybatis")
@Api("主类管理")
public class MybatisController {
@Autowired
MybatisService mybatisService;
@ApiOperation("查询")
@GetMapping("page/{offset}/{limit}")
public List<User> getPage(@PathVariable Integer offset, @PathVariable Integer limit){
return mybatisService.getPageList(offset, limit);
}
@ApiOperation("通过id查询")
@GetMapping("page/{userId}")
public Map getAll(@PathVariable Integer userId){
HashMap<String, Object> map = new HashMap<>();
map.put("kang",mybatisService.getAll(userId).toString());
System.out.println(map);
return map;
}
@ApiOperation("插入")
@PostMapping("/insert")
public Integer insert(@RequestParam Integer userId, @RequestParam String userName){
return mybatisService.insert(userId, userName);
}
@ApiOperation("更新")
@PutMapping("update/{userId}/{userName}")
public Integer update(@PathVariable Integer userId, @PathVariable String userName){
return mybatisService.update(userId, userName);
}
@ApiOperation("删除")
@DeleteMapping("delete")
public Integer delete(@RequestParam Integer userId){
return mybatisService.delete(userId);
}
@ApiOperation("插入")
@PostMapping("insert1")
public User insert1(@RequestBody User user){
mybatisService.insert1(user);
return user;
}
/**
* 导出excel
*/
@ApiOperation("导出excel")
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) {
mybatisService.exportExcel(response);
}
}
MybatisService:
package com.springboot.MyMybatis.service;
import com.springboot.MyMybatis.entity.User;
import com.springboot.MyMybatis.mapper.MybatisMapper;
import com.springboot.MyMybatis.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Service
public class MybatisService {
@Autowired
MybatisMapper mybatisMapper;
public List<User> getPageList(Integer offset, Integer limit){
// 测试全局异常捕获
List<String> list = null;
list.add("a");
return mybatisMapper.getPageList(offset, limit);
}
public User getAll(Integer userId) {
return mybatisMapper.getAll(userId);
}
public Integer insert(Integer userId, String userName) {
return mybatisMapper.insert(userId, userName);
}
public Integer update(Integer userId, String userName) {
return mybatisMapper.update(userId, userName);
}
public Integer delete(Integer userId) {
return mybatisMapper.delete(userId);
}
public Integer insert1(User user) {
return mybatisMapper.insert1(user);
}
public void exportExcel(HttpServletResponse response) {
List<User> list = mybatisMapper.selectUserList();
try {
ExcelUtils.exportData(response,"求救信息", "sheet1", User.class, list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MybatisMapper:
package com.springboot.MyMybatis.mapper;
import com.springboot.MyMybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface MybatisMapper {
User getAll(Integer userId);
Integer insert(Integer userId, String userName);
Integer update(Integer userId, String userName);
Integer delete(Integer userId);
Integer insert1(@Param("param") User user);
List<User> selectUserList();
List<User> getPageList(@Param("offset") Integer offset, @Param("limit") Integer limit);
}
MybatisMapper.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.springboot.MyMybatis.mapper.MybatisMapper">
<!-- 这个cache 是关键 -->
<cache eviction="LRU" flushInterval="100000" readOnly="true" size="1024"/>
<resultMap id="userInfo" type="com.springboot.MyMybatis.entity.User">
<id property="userId" column="user_id" />
<result property="userName" column="user_name" />
</resultMap>
<select id="getAll" resultMap="userInfo">
select user_id,user_name from user t where user_id = #{userId}
</select>
<select id="selectUserList" resultMap="userInfo">
select user_id,user_name from user t
</select>
<select id="getPageList" resultType="com.springboot.MyMybatis.entity.User">
select *
from `user`
<if test="limit != null ">
<if test="offset != null">
limit #{offset},#{limit}
</if>
<if test="offset == null">
limit #{limit}
</if>
</if>
</select>
<insert id="insert">
insert user (user_id, user_name) values (#{userId},#{userName})
</insert>
<insert id="insert1">
insert user (user_id, user_name) values (#{param.userId},#{param.userName})
</insert>
<update id="update">
update user set user_name = #{userName} where user_id = #{userId}
</update>
<delete id="delete">
delete from user where user_id = #{userId}
</delete>
</mapper>
application.properties:
server.port=8088
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root123
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#配置mapper的扫描路径
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
#mybatis.configuration.cache-enabled=true
#开启sql日志打印
logging.level.com.springboot.MyMybatis=debug
spring.rabbitmq.addresses=10.1.153.70:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
#swagger 2.9.0以上版本使用
#spring.mvc.pathmatch.matching-strategy=ant_path_matcher
package com.springboot.MyMybatis.utils;
import com.springboot.MyMybatis.constant.CommonConstants;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 响应信息主体
*
* @param <T>
* @author lengleng
*/
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@Setter
private int code;
@Getter
@Setter
private String msg;
@Getter
@Setter
private T data;
public static <T> R<T> ok() {
return restResult(null, CommonConstants.SUCCESS, null);
}
public static <T> R<T> ok(T data) {
return restResult(data, CommonConstants.SUCCESS, null);
}
public static <T> R<T> ok(T data, String msg) {
return restResult(data, CommonConstants.SUCCESS, msg);
}
public static <T> R<T> failed() {
return restResult(null, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(String msg) {
return restResult(null, CommonConstants.FAIL, msg);
}
public static <T> R<T> failed(T data) {
return restResult(data, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(T data, String msg) {
return restResult(data, CommonConstants.FAIL, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
}
package com.springboot.MyMybatis.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author tian meng
* @date 2022/7/20
*/
@Configuration //声明该类为配置类
@EnableSwagger2 //声明启动Swagger2
@EnableKnife4j
public class SwaggerConfig{
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.springboot.MyMybatis.controller"))//扫描的包路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试swagger")//文档说明
.version("1.0.0")//文档版本说明
.build();
}
}