java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot整合mybatisplus和druid

SpringBoot整合mybatisplus和druid的示例详解

作者:fking86

这篇文章主要介绍了SpringBoot整合mybatisplus和druid的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

版本介绍

jdk 17

SpringBoot 3.1.0

druid-spring-boot-starter 1.2.4

mysql-connector 8.0.33

mybatis-plus 3.5.3.1

环境准备

导入依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.0</version>
</parent>
<properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <druid.version>1.2.4</druid.version>
        <mysql.version>8.0.33</mysql.version>
        <lombok.version>1.18.26</lombok.version>
        <swagger.version>1.5.22</swagger.version>
        <mybatis-plus.version>3.5.3.1</mybatis-plus.version>
</properties>
<!-- Web 相关 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- swagger -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>${swagger.version}</version>
            <scope>compile</scope>
        </dependency>

application.yml配置

server:
  port: 8080
spring:
  datasource:
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/springboot-exp?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&AllowPublicKeyRetrieval=True
    username: root
    password: 123456
    # 数据源连接池配置
    druid:
      #   数据源其他配置
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.logSlowSql=true;druid.stat.slowSqlMillis=1000;
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml # xml路径
  global-config:
    db-config:
      id-type: ASSIGN_ID # 全局默认主键策略,默认为雪花ID,若表中设置了自增,则生成的实体自动添加自增ID属性,参考 TestDelete
      logic-delete-field: deleted # 全局逻辑删除的实体字段名,若不配置,则不启用
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
  configuration:
    map-underscore-to-camel-case: true # 驼峰转下划线(默认)
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志输出
  type-aliases-package: com.example.domain.entity

数据库表

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `user_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名字',
  `password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户密码',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

使用

MybatisPlusConfig

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 添加 攻击 SQL 阻断解析器,防止全表更新与删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        // 添加 乐观锁 插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

User

@TableName(value = "user", autoResultMap = true)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -4328989516223829865L;
    /**
     * 用户ID
     */
    @TableId
    private String id;
    /**
     * 用户账号
     */
    private String userName;
    /**
     * 密码
     */
    private String password;
}

UserMapper

@Mapper
public interface UserMapper extends BaseMapper<User> {}

UserService

public interface UserService {
    void save(User user);
    User getById(String id);
    void removeById(String id);
    void update(UserUpdateReqVO reqVO);
}

UserBaseVO

@ApiModel("Request VO")
@Data
@ToString(callSuper = true)
public class UserBaseVO {
    @ApiModelProperty(value = "用户名字", required = true)
    @NotNull(message = "用户名字不能为空")
    private String username;
    @ApiModelProperty(value = "用户密码", required = true)
    @NotNull(message = "用户密码不能为空")
    private String password;
}

UserUpdateReqVO

@ApiModel("用户更新 Request VO")
@Data
@ToString(callSuper = true)
public class UserUpdateReqVO extends UserBaseVO {
    @ApiModelProperty(value = "", required = true)
    @NotNull(message = "id不能为空")
    private String id;
}

UserCreateReqVO

@ApiModel("用户更新 Request VO")
@Data
@ToString(callSuper = true)
public class UserCreateReqVO extends UserBaseVO {
}

MyBatisDemoController

@RestController
@RequestMapping("/user")
@Slf4j
public class MyBatisDemoController {
    @Autowired
    private UserService userService;
    /**
     * 添加一个新用户
     *
     * @return java.lang.Object
     */
    @GetMapping("/add")
    public Object add(UserCreateReqVO reqVO) {
        User user = User.builder().id(UUID.randomUUID().toString()).password(reqVO.getPassword()).userName(reqVO.getUsername()).build();
        userService.save(user);
        return "add";
    }
    /**
     * 更新用户
     *
     * @return java.lang.Object
     */
    @GetMapping("/update")
    public Object update(@RequestBody UserUpdateReqVO reqVO) {
        User user = userService.getById(reqVO.getId());
        if(null != user){
            userService.update(reqVO);
            return "update success";
        }
        return "update error";
    }
    /**
     * 通过id获取用户
     *
     * @param id
     * @return java.lang.Object
     */
    @GetMapping("/{id}")
    public Object get(@PathVariable String id) {
        return userService.getById(id);
    }
    /**
     * 通过id删除用户
     *
     * @param id
     * @return java.lang.Object
     */
    @GetMapping("/del/{id}")
    public Object del(@PathVariable String id) {
        userService.removeById(id);
        return "del";
    }
}

代码生成工具

导入依赖

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>

GeneratorUtils

public class GeneratorUtils {
        public static void main(String[] args) {
        autoGenerator();
        }
        public static void autoGenerator() {
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setDataSource(getDataSourceConfig());
        autoGenerator.setGlobalConfig(getGlobalConfig());
        autoGenerator.setPackageInfo(getPackageInfo());
        autoGenerator.setStrategy(getStrategyConfig());
        autoGenerator.execute();
        }
        /**
        * 设置数据源
        * @return
        */
        public static DataSourceConfig getDataSourceConfig(){
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://47.98.123.147:3306/springboot-exp?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&AllowPublicKeyRetrieval=True");
        dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("springboot-exp");
        dsc.setPassword("HJRNEhKPS8MPapB8");
        dsc.setDbType(DbType.MYSQL);
        return dsc;
        }
        /**
        * 设置全局配置
        * @return
        */
        public static GlobalConfig getGlobalConfig(){
        GlobalConfig gc = new GlobalConfig();
        String path = System.getProperty("user.dir");
        gc.setOutputDir(path+"/springboot-mybatisplus-druid/src/main/java");//参数是一个目录,所以需要获取当前系统目录
        gc.setAuthor("coderjim");
        gc.setOpen(true);//是否打开资源管理器
        gc.setFileOverride(true);//是否覆盖已经生成的
        gc.setServiceName("%sService");//去service的I前缀
        gc.setIdType(IdType.INPUT);// id生成策略
        gc.setDateType(DateType.ONLY_DATE);
        return gc;
        }
        /**
        *包配置
        * @return
        */
        public static PackageConfig getPackageInfo(){
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("common");
        pc.setParent("com.example");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        return pc;
        }
        /**
        * 策略配置
        * @return
        */
        public static StrategyConfig getStrategyConfig(){
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);// 下划线转驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 设置映射的表名,多张表
        strategy.setInclude("user");
        strategy.setEntityLombokModel(true);// 是否启用lombok开启注解
        strategy.setLogicDeleteFieldName("isAction");//设置逻辑删除字段
        // 时间自动填充配置
        TableFill startDate = new TableFill("startDate", FieldFill.INSERT);
        TableFill updateDate = new TableFill("updateDate", FieldFill.UPDATE);
        ArrayList<TableFill> list = new ArrayList<>();
        list.add(startDate);
        list.add(updateDate);
        strategy.setTableFillList(list);
        // 乐观锁配置
        strategy.setVersionFieldName("version");
        // rustful 格式
        strategy.setRestControllerStyle(true);
        return  strategy;
        }
}

以上就是SpringBoot整合mybatisplus和druid的示例详解的详细内容,更多关于SpringBoot整合mybatisplus和druid的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文