源代码
一、项目配置
1、项目yml
server:
port: 9188
spring:
application:
name: git-test3
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://x.x.x.x:3306/mytest?serverTimezone=UTC&useSSL=false
username: azhi
password: azhi2021888
2、项目pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
</parent>
<dependencies>
<!--spring-boot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--mybatis-plus依赖,如果冲突,这里就用3.4.1版本,和mybatis-plus-generator一致-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<!--generator代码生成依赖,要注意mybatis-plus和generator的版本比较容易冲突-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--freemarker代码生成模板依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!--entity中Data依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!--swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--swagger-bootstrap-ui-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
3、Generator自动代码生成类:
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
public class CodeGenerator {
private static String[] tables = new String[]{"user","order"};
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("azhi");
gc.setOpen(false);
gc.setSwagger2(true); //entity实体属性添加Swagger2注解ApiModel
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://x.x.x.x:3306/mytest?serverTimezone=UTC&useSSL=false");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("azhi");
dsc.setPassword("azhi2021888");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.azhi.gitTest3");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/"
// + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("com.snow.management.controller.BaseController");//你自己的父类控制器,没有就不用设置!
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");//生成的实体类没有id字段
// strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setInclude(tables);
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
4、swagger3配置类
import io.swagger.annotations.ApiOperation;
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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
//swagger设置,基本信息,要解析的接口及路径等
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
//设置通过什么方式定位需要自动生成文档的接口,这里定位方法上的@ApiOperation注解
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//接口URI路径设置,any是全路径,也可以通过PathSelectors.regex()正则匹配
.paths(PathSelectors.any())
.build();
}
//生成接口信息,包括标题、联系人,联系方式等
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("如有疑问,请联系开发工程师")
.contact(new Contact("denglinzhi", "https://www.yuque.com/docs/share/3994dcb3-4358-4c02-9d9b-510d4877f601", "913240792@qq.com"))
.version("1.0")
.build();
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.net.Inet4Address;
import java.net.UnknownHostException;
/**
* @Description 控制台输出 Swagger3 接口文档地址
**/
@Component
@Slf4j
public class SwaggerPrintConfig implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
try {
//获取IP
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
//获取端口号
int port = event.getWebServer().getPort();
//获取应用名
String applicationName = event.getApplicationContext().getApplicationName();
//log.info("项目启动启动成功!Swagger3接口文档地址: http://"+hostAddress+":"+event.getWebServer().getPort()+applicationName+"/swagger-ui/index.html");
log.info("项目启动启动成功!Swagger3接口文档地址: http://"+hostAddress+":"+event.getWebServer().getPort()+applicationName+"/doc.html");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
5、mybatiesplus分页配置类
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//Spring boot方式
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* 旧版本配置,分页插件
*
*/
/*@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}*/
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,
* 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
* 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
二、进行CURD测试
1、写user实体类
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author azhi
* @since 2021-11-28
*/
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="User对象", description="")
public class User implements Serializable {
@ApiModelProperty(value = "自增id", example = "", required = true)
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "自增id", example = "", required = true)
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "用户名称", example = "", required = true)
private String name;
}
2、写xml mapper
<?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.azhi.gitTest3.mapper.UserMapper">
<select id="selectAllUser" parameterType="int" resultType="com.azhi.gitTest3.entity.User">
select id,name from user
</select>
<select id="selectUserByUserId" parameterType="int" resultType="com.azhi.gitTest3.entity.User">
select id,name from user where id = #{user_id}
</select>
<select id="selectUserByPage" resultType="com.azhi.gitTest3.entity.User">
select id,name from user ${ew.customSqlSegment}
</select>
<select id="selectUserByPage1" resultType="com.azhi.gitTest3.entity.User" parameterType="com.azhi.gitTest3.entity.User">
select id,name from user
<where>
<if test="et.id != null ">and id = #{et.id}</if>
<if test="et.name != null ">and name = #{et.name}</if>
</where>
</select>
<insert id="addUserBatch" parameterType="com.azhi.gitTest3.entity.User">
insert into user (id,name) values
<foreach collection="listUser" item="user" separator=",">
(#{user.id},#{user.name})
</foreach>
</insert>
</mapper>
3、映射xml mapper
import com.azhi.gitTest3.entity.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author azhi
* @since 2021-11-28
*/
@Service
public interface UserMapper extends BaseMapper<User> {
List<User> selectAllUser();
User selectUserByUserId(int user_id);
IPage<User> selectUserByPage(IPage<User> userPage , @Param(Constants.WRAPPER) Wrapper<User> userWrapper);
IPage<User> selectUserByPage1(IPage<User> userPage , @Param(Constants.ENTITY) User user);
int addUserBatch(@Param("listUser")List<User> listUser);
}
4、写IUserService
import com.azhi.gitTest3.entity.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author azhi
* @since 2021-11-28
*/
public interface IUserService extends IService<User> {
List<User> selectAllUser();
User selectUserByUserId(int user_id);
IPage<User> selectUserByPage(IPage<User> userPage , @Param(Constants.WRAPPER) Wrapper<User> userWrapper);
IPage<User> selectUserByPage1(IPage<User> userPage , @Param(Constants.ENTITY) User user);
int addUserBatch(@Param("listUser")List<User> listUser);
}
5、写UserServiceImpl
import com.azhi.gitTest3.entity.User;
import com.azhi.gitTest3.mapper.UserMapper;
import com.azhi.gitTest3.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author azhi
* @since 2021-11-28
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> selectAllUser() {
return userMapper.selectAllUser();
}
@Override
public User selectUserByUserId(int user_id) {
return userMapper.selectUserByUserId(user_id);
}
@Override
public IPage<User> selectUserByPage(IPage<User> userPage, Wrapper<User> userWrapper) {
return userMapper.selectUserByPage(userPage, userWrapper);
}
@Override
public IPage<User> selectUserByPage1(IPage<User> userPage, User user) {
return userMapper.selectUserByPage1(userPage, user);
}
@Override
public int addUserBatch(List<User> listUser) {
return userMapper.addUserBatch(listUser);
}
}
6、controller中调用
import com.azhi.gitTest3.entity.User;
import com.azhi.gitTest3.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @author azhi
* @since 2021-11-28
*/
@RestController
@RequestMapping("/user")
@Api(tags = "测试用户控制类")
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/login")
@ApiOperation(value = "测试login方法")
public User login() {
System.out.println("ok");
User user = userService.selectUserByUserId(1);
return user;
}
@GetMapping("/all")
@ApiOperation(value = "测试all方法")
public List<User> all() {
System.out.println("ok");
List<User> users = userService.selectAllUser();
return users;
}
@GetMapping("/page")
@ApiOperation(value = "测试page分页方法")
public IPage<User> page() {
System.out.println("ok");
Integer pageNo = 1;
Integer pageSize = 10;
IPage<User> page = new Page<>(pageNo, pageSize,true);
QueryWrapper<User> wrapper = new QueryWrapper<>();
User user = new User();
user.setId(1);
wrapper.setEntity(user);
//IPage<User> result = userService.page(page,null);
IPage<User> result = userService.page(page,wrapper);
return result;
}
@GetMapping("/xmlPage")
@ApiOperation(value = "测试xmlPage分页方法")
public IPage<User> xmlPage() {
LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
userLambdaQueryWrapper.like(User::getId , 1);
Page<User> page = new Page<>(1 , 2 , true);
IPage<User> mapIPage = userService.selectUserByPage(page , userLambdaQueryWrapper);
return mapIPage;
}
@GetMapping("/xmlPage1")
@ApiOperation(value = "测试xmlPage1分页方法")
public IPage<User> xmlPage1() {
Page<User> page = new Page<>(1 , 2 , true);
User user = new User();
user.setId(1);
IPage<User> mapIPage = userService.selectUserByPage1(page , user);
return mapIPage;
}
@GetMapping("/addBatch")
@ApiOperation(value = "测试addBatch批量添加用户方法")
public int addBatch() {
List<User> list = new ArrayList<>();
for(int id = 3;id<6;id++){
User user = new User();
user.setId(id);
user.setName(id+"");
list.add(user);
}
int count = userService.addUserBatch(list);
return count;
}
}
三、测试文档
也可以用doc文档,http://192.168.1.8:9522/doc.html,如下: