源代码

一、项目配置

1、项目yml

  1. server:
  2. port: 9188
  3. spring:
  4. application:
  5. name: git-test3
  6. datasource:
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. url: jdbc:mysql://x.x.x.x:3306/mytest?serverTimezone=UTC&useSSL=false
  9. username: azhi
  10. password: azhi2021888

2、项目pom.xml

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.3.9.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <!--spring-boot-->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-web</artifactId>
  15. </dependency>
  16. <!--mysql相关依赖-->
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-jdbc</artifactId>
  20. <version>2.3.9.RELEASE</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <version>8.0.26</version>
  26. </dependency>
  27. <!--mybatis-plus依赖,如果冲突,这里就用3.4.1版本,和mybatis-plus-generator一致-->
  28. <dependency>
  29. <groupId>com.baomidou</groupId>
  30. <artifactId>mybatis-plus-boot-starter</artifactId>
  31. <version>3.4.3.4</version>
  32. </dependency>
  33. <!--generator代码生成依赖,要注意mybatis-plusgenerator的版本比较容易冲突-->
  34. <dependency>
  35. <groupId>com.baomidou</groupId>
  36. <artifactId>mybatis-plus-generator</artifactId>
  37. <version>3.4.1</version>
  38. </dependency>
  39. <!--freemarker代码生成模板依赖-->
  40. <dependency>
  41. <groupId>org.freemarker</groupId>
  42. <artifactId>freemarker</artifactId>
  43. <version>2.3.31</version>
  44. </dependency>
  45. <!--entityData依赖-->
  46. <dependency>
  47. <groupId>org.projectlombok</groupId>
  48. <artifactId>lombok</artifactId>
  49. <version>1.18.20</version>
  50. </dependency>
  51. <!--swagger3-->
  52. <dependency>
  53. <groupId>io.springfox</groupId>
  54. <artifactId>springfox-boot-starter</artifactId>
  55. <version>3.0.0</version>
  56. </dependency>
  57. <!--swagger-bootstrap-ui-->
  58. <dependency>
  59. <groupId>com.github.xiaoymin</groupId>
  60. <artifactId>swagger-bootstrap-ui</artifactId>
  61. <version>1.9.6</version>
  62. </dependency>
  63. </dependencies>
  64. <build>
  65. <finalName>${project.artifactId}</finalName>
  66. <plugins>
  67. <plugin>
  68. <groupId>org.springframework.boot</groupId>
  69. <artifactId>spring-boot-maven-plugin</artifactId>
  70. </plugin>
  71. </plugins>
  72. </build>

3、Generator自动代码生成类:

  1. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  2. import com.baomidou.mybatisplus.generator.AutoGenerator;
  3. import com.baomidou.mybatisplus.generator.InjectionConfig;
  4. import com.baomidou.mybatisplus.generator.config.*;
  5. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  6. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  7. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. public class CodeGenerator {
  11. private static String[] tables = new String[]{"user","order"};
  12. public static void main(String[] args) {
  13. // 代码生成器
  14. AutoGenerator mpg = new AutoGenerator();
  15. // 全局配置
  16. GlobalConfig gc = new GlobalConfig();
  17. String projectPath = System.getProperty("user.dir");
  18. gc.setOutputDir(projectPath + "/src/main/java");
  19. gc.setAuthor("azhi");
  20. gc.setOpen(false);
  21. gc.setSwagger2(true); //entity实体属性添加Swagger2注解ApiModel
  22. mpg.setGlobalConfig(gc);
  23. // 数据源配置
  24. DataSourceConfig dsc = new DataSourceConfig();
  25. dsc.setUrl("jdbc:mysql://x.x.x.x:3306/mytest?serverTimezone=UTC&useSSL=false");
  26. // dsc.setSchemaName("public");
  27. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
  28. dsc.setUsername("azhi");
  29. dsc.setPassword("azhi2021888");
  30. mpg.setDataSource(dsc);
  31. // 包配置
  32. PackageConfig pc = new PackageConfig();
  33. pc.setParent("com.azhi.gitTest3");
  34. mpg.setPackageInfo(pc);
  35. // 自定义配置
  36. InjectionConfig cfg = new InjectionConfig() {
  37. @Override
  38. public void initMap() {
  39. // to do nothing
  40. }
  41. };
  42. // 如果模板引擎是 freemarker
  43. String templatePath = "/templates/mapper.xml.ftl";
  44. // 如果模板引擎是 velocity
  45. // String templatePath = "/templates/mapper.xml.vm";
  46. // 自定义输出配置
  47. List<FileOutConfig> focList = new ArrayList<>();
  48. // 自定义配置会被优先输出
  49. focList.add(new FileOutConfig(templatePath) {
  50. @Override
  51. public String outputFile(TableInfo tableInfo) {
  52. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  53. return projectPath + "/src/main/resources/mapper/"
  54. // + pc.getModuleName()
  55. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  56. }
  57. });
  58. /*
  59. cfg.setFileCreate(new IFileCreate() {
  60. @Override
  61. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
  62. // 判断自定义文件夹是否需要创建
  63. checkDir("调用默认方法创建的目录");
  64. return false;
  65. }
  66. });
  67. */
  68. cfg.setFileOutConfigList(focList);
  69. mpg.setCfg(cfg);
  70. // 配置模板
  71. TemplateConfig templateConfig = new TemplateConfig();
  72. // 配置自定义输出模板
  73. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  74. // templateConfig.setEntity("templates/entity2.java");
  75. // templateConfig.setService();
  76. // templateConfig.setController();
  77. templateConfig.setXml(null);
  78. mpg.setTemplate(templateConfig);
  79. // 策略配置
  80. StrategyConfig strategy = new StrategyConfig();
  81. strategy.setNaming(NamingStrategy.underline_to_camel);
  82. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  83. // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
  84. strategy.setEntityLombokModel(true);
  85. strategy.setRestControllerStyle(true);
  86. // 公共父类
  87. // strategy.setSuperControllerClass("com.snow.management.controller.BaseController");//你自己的父类控制器,没有就不用设置!
  88. // 写于父类中的公共字段
  89. // strategy.setSuperEntityColumns("id");//生成的实体类没有id字段
  90. // strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
  91. strategy.setInclude(tables);
  92. strategy.setControllerMappingHyphenStyle(true);
  93. // strategy.setTablePrefix(pc.getModuleName() + "_");
  94. mpg.setStrategy(strategy);
  95. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  96. mpg.execute();
  97. }
  98. }

4、swagger3配置类

  1. import io.swagger.annotations.ApiOperation;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import springfox.documentation.builders.ApiInfoBuilder;
  5. import springfox.documentation.builders.PathSelectors;
  6. import springfox.documentation.builders.RequestHandlerSelectors;
  7. import springfox.documentation.oas.annotations.EnableOpenApi;
  8. import springfox.documentation.service.ApiInfo;
  9. import springfox.documentation.service.Contact;
  10. import springfox.documentation.spi.DocumentationType;
  11. import springfox.documentation.spring.web.plugins.Docket;
  12. @EnableOpenApi
  13. @Configuration
  14. public class SwaggerConfig {
  15. @Bean
  16. public Docket createRestApi() {
  17. //swagger设置,基本信息,要解析的接口及路径等
  18. return new Docket(DocumentationType.OAS_30)
  19. .apiInfo(apiInfo())
  20. .select()
  21. //设置通过什么方式定位需要自动生成文档的接口,这里定位方法上的@ApiOperation注解
  22. .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  23. //接口URI路径设置,any是全路径,也可以通过PathSelectors.regex()正则匹配
  24. .paths(PathSelectors.any())
  25. .build();
  26. }
  27. //生成接口信息,包括标题、联系人,联系方式等
  28. private ApiInfo apiInfo() {
  29. return new ApiInfoBuilder()
  30. .title("Swagger3接口文档")
  31. .description("如有疑问,请联系开发工程师")
  32. .contact(new Contact("denglinzhi", "https://www.yuque.com/docs/share/3994dcb3-4358-4c02-9d9b-510d4877f601", "913240792@qq.com"))
  33. .version("1.0")
  34. .build();
  35. }
  36. }
  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.boot.web.context.WebServerInitializedEvent;
  3. import org.springframework.context.ApplicationListener;
  4. import org.springframework.stereotype.Component;
  5. import java.net.Inet4Address;
  6. import java.net.UnknownHostException;
  7. /**
  8. * @Description 控制台输出 Swagger3 接口文档地址
  9. **/
  10. @Component
  11. @Slf4j
  12. public class SwaggerPrintConfig implements ApplicationListener<WebServerInitializedEvent> {
  13. @Override
  14. public void onApplicationEvent(WebServerInitializedEvent event) {
  15. try {
  16. //获取IP
  17. String hostAddress = Inet4Address.getLocalHost().getHostAddress();
  18. //获取端口号
  19. int port = event.getWebServer().getPort();
  20. //获取应用名
  21. String applicationName = event.getApplicationContext().getApplicationName();
  22. //log.info("项目启动启动成功!Swagger3接口文档地址: http://"+hostAddress+":"+event.getWebServer().getPort()+applicationName+"/swagger-ui/index.html");
  23. log.info("项目启动启动成功!Swagger3接口文档地址: http://"+hostAddress+":"+event.getWebServer().getPort()+applicationName+"/doc.html");
  24. } catch (UnknownHostException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }

5、mybatiesplus分页配置类

  1. import com.baomidou.mybatisplus.annotation.DbType;
  2. import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
  3. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  4. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
  5. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.transaction.annotation.EnableTransactionManagement;
  9. //Spring boot方式
  10. @EnableTransactionManagement
  11. @Configuration
  12. public class MybatisPlusConfig {
  13. /**
  14. * 旧版本配置,分页插件
  15. *
  16. */
  17. /*@Bean
  18. public PaginationInterceptor paginationInterceptor(){
  19. return new PaginationInterceptor();
  20. }*/
  21. /**
  22. * 新的分页插件,一缓和二缓遵循mybatis的规则,
  23. * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
  24. * 避免缓存出现问题(该属性会在旧插件移除后一同移除)
  25. */
  26. @Bean
  27. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  28. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  29. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
  30. return interceptor;
  31. }
  32. @Bean
  33. public ConfigurationCustomizer configurationCustomizer() {
  34. return configuration -> configuration.setUseDeprecatedExecutor(false);
  35. }
  36. }

二、进行CURD测试

1、写user实体类

  1. import com.baomidou.mybatisplus.annotation.IdType;
  2. import com.baomidou.mybatisplus.annotation.TableId;
  3. import java.io.Serializable;
  4. import io.swagger.annotations.ApiModel;
  5. import io.swagger.annotations.ApiModelProperty;
  6. import lombok.Data;
  7. import lombok.EqualsAndHashCode;
  8. /**
  9. * @author azhi
  10. * @since 2021-11-28
  11. */
  12. @Data
  13. @EqualsAndHashCode(callSuper = false)
  14. @ApiModel(value="User对象", description="")
  15. public class User implements Serializable {
  16. @ApiModelProperty(value = "自增id", example = "", required = true)
  17. private static final long serialVersionUID = 1L;
  18. @ApiModelProperty(value = "自增id", example = "", required = true)
  19. @TableId(value = "id", type = IdType.AUTO)
  20. private Integer id;
  21. @ApiModelProperty(value = "用户名称", example = "", required = true)
  22. private String name;
  23. }

2、写xml mapper

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.azhi.gitTest3.mapper.UserMapper">
  4. <select id="selectAllUser" parameterType="int" resultType="com.azhi.gitTest3.entity.User">
  5. select id,name from user
  6. </select>
  7. <select id="selectUserByUserId" parameterType="int" resultType="com.azhi.gitTest3.entity.User">
  8. select id,name from user where id = #{user_id}
  9. </select>
  10. <select id="selectUserByPage" resultType="com.azhi.gitTest3.entity.User">
  11. select id,name from user ${ew.customSqlSegment}
  12. </select>
  13. <select id="selectUserByPage1" resultType="com.azhi.gitTest3.entity.User" parameterType="com.azhi.gitTest3.entity.User">
  14. select id,name from user
  15. <where>
  16. <if test="et.id != null ">and id = #{et.id}</if>
  17. <if test="et.name != null ">and name = #{et.name}</if>
  18. </where>
  19. </select>
  20. <insert id="addUserBatch" parameterType="com.azhi.gitTest3.entity.User">
  21. insert into user (id,name) values
  22. <foreach collection="listUser" item="user" separator=",">
  23. (#{user.id},#{user.name})
  24. </foreach>
  25. </insert>
  26. </mapper>

3、映射xml mapper

  1. import com.azhi.gitTest3.entity.User;
  2. import com.baomidou.mybatisplus.core.conditions.Wrapper;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import com.baomidou.mybatisplus.core.metadata.IPage;
  5. import com.baomidou.mybatisplus.core.toolkit.Constants;
  6. import org.apache.ibatis.annotations.Param;
  7. import org.springframework.stereotype.Service;
  8. import java.util.List;
  9. /**
  10. * @author azhi
  11. * @since 2021-11-28
  12. */
  13. @Service
  14. public interface UserMapper extends BaseMapper<User> {
  15. List<User> selectAllUser();
  16. User selectUserByUserId(int user_id);
  17. IPage<User> selectUserByPage(IPage<User> userPage , @Param(Constants.WRAPPER) Wrapper<User> userWrapper);
  18. IPage<User> selectUserByPage1(IPage<User> userPage , @Param(Constants.ENTITY) User user);
  19. int addUserBatch(@Param("listUser")List<User> listUser);
  20. }

4、写IUserService

  1. import com.azhi.gitTest3.entity.User;
  2. import com.baomidou.mybatisplus.core.conditions.Wrapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.core.toolkit.Constants;
  5. import com.baomidou.mybatisplus.extension.service.IService;
  6. import org.apache.ibatis.annotations.Param;
  7. import java.util.List;
  8. /**
  9. * @author azhi
  10. * @since 2021-11-28
  11. */
  12. public interface IUserService extends IService<User> {
  13. List<User> selectAllUser();
  14. User selectUserByUserId(int user_id);
  15. IPage<User> selectUserByPage(IPage<User> userPage , @Param(Constants.WRAPPER) Wrapper<User> userWrapper);
  16. IPage<User> selectUserByPage1(IPage<User> userPage , @Param(Constants.ENTITY) User user);
  17. int addUserBatch(@Param("listUser")List<User> listUser);
  18. }

5、写UserServiceImpl

  1. import com.azhi.gitTest3.entity.User;
  2. import com.azhi.gitTest3.mapper.UserMapper;
  3. import com.azhi.gitTest3.service.IUserService;
  4. import com.baomidou.mybatisplus.core.conditions.Wrapper;
  5. import com.baomidou.mybatisplus.core.metadata.IPage;
  6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import java.util.List;
  10. /**
  11. * @author azhi
  12. * @since 2021-11-28
  13. */
  14. @Service
  15. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
  16. @Autowired
  17. UserMapper userMapper;
  18. @Override
  19. public List<User> selectAllUser() {
  20. return userMapper.selectAllUser();
  21. }
  22. @Override
  23. public User selectUserByUserId(int user_id) {
  24. return userMapper.selectUserByUserId(user_id);
  25. }
  26. @Override
  27. public IPage<User> selectUserByPage(IPage<User> userPage, Wrapper<User> userWrapper) {
  28. return userMapper.selectUserByPage(userPage, userWrapper);
  29. }
  30. @Override
  31. public IPage<User> selectUserByPage1(IPage<User> userPage, User user) {
  32. return userMapper.selectUserByPage1(userPage, user);
  33. }
  34. @Override
  35. public int addUserBatch(List<User> listUser) {
  36. return userMapper.addUserBatch(listUser);
  37. }
  38. }

6、controller中调用

  1. import com.azhi.gitTest3.entity.User;
  2. import com.azhi.gitTest3.service.IUserService;
  3. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  4. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5. import com.baomidou.mybatisplus.core.metadata.IPage;
  6. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  7. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  8. import io.swagger.annotations.Api;
  9. import io.swagger.annotations.ApiOperation;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. /**
  17. * @author azhi
  18. * @since 2021-11-28
  19. */
  20. @RestController
  21. @RequestMapping("/user")
  22. @Api(tags = "测试用户控制类")
  23. public class UserController {
  24. @Autowired
  25. private IUserService userService;
  26. @GetMapping("/login")
  27. @ApiOperation(value = "测试login方法")
  28. public User login() {
  29. System.out.println("ok");
  30. User user = userService.selectUserByUserId(1);
  31. return user;
  32. }
  33. @GetMapping("/all")
  34. @ApiOperation(value = "测试all方法")
  35. public List<User> all() {
  36. System.out.println("ok");
  37. List<User> users = userService.selectAllUser();
  38. return users;
  39. }
  40. @GetMapping("/page")
  41. @ApiOperation(value = "测试page分页方法")
  42. public IPage<User> page() {
  43. System.out.println("ok");
  44. Integer pageNo = 1;
  45. Integer pageSize = 10;
  46. IPage<User> page = new Page<>(pageNo, pageSize,true);
  47. QueryWrapper<User> wrapper = new QueryWrapper<>();
  48. User user = new User();
  49. user.setId(1);
  50. wrapper.setEntity(user);
  51. //IPage<User> result = userService.page(page,null);
  52. IPage<User> result = userService.page(page,wrapper);
  53. return result;
  54. }
  55. @GetMapping("/xmlPage")
  56. @ApiOperation(value = "测试xmlPage分页方法")
  57. public IPage<User> xmlPage() {
  58. LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
  59. userLambdaQueryWrapper.like(User::getId , 1);
  60. Page<User> page = new Page<>(1 , 2 , true);
  61. IPage<User> mapIPage = userService.selectUserByPage(page , userLambdaQueryWrapper);
  62. return mapIPage;
  63. }
  64. @GetMapping("/xmlPage1")
  65. @ApiOperation(value = "测试xmlPage1分页方法")
  66. public IPage<User> xmlPage1() {
  67. Page<User> page = new Page<>(1 , 2 , true);
  68. User user = new User();
  69. user.setId(1);
  70. IPage<User> mapIPage = userService.selectUserByPage1(page , user);
  71. return mapIPage;
  72. }
  73. @GetMapping("/addBatch")
  74. @ApiOperation(value = "测试addBatch批量添加用户方法")
  75. public int addBatch() {
  76. List<User> list = new ArrayList<>();
  77. for(int id = 3;id<6;id++){
  78. User user = new User();
  79. user.setId(id);
  80. user.setName(id+"");
  81. list.add(user);
  82. }
  83. int count = userService.addUserBatch(list);
  84. return count;
  85. }
  86. }

三、测试文档

image.png
image.png
也可以用doc文档,http://192.168.1.8:9522/doc.html,如下:
image.png