SpringBoot整合mybatisplus和druid


579a429daf314744b995f37351b46548

前言

在现代软件开发中,使用框架可以大大提高开发效率和代码质量。

Spring Boot 是一个快速开发框架,它简化了 Spring 应用的配置和部署过程。

MyBatis-Plus 是一个基于 MyBatis 的增强工具,它可以简化数据库操作,提高开发效率。

Druid 是一个高性能的数据库连接池,它可以提高数据库访问性能。本文将介绍如何在 Spring Boot 项目中整合 MyBatis-Plus 和 Druid,实现数据库操作和连接池管理。


版本介绍

模块版本号
JDK17
SpringBoot3.1.0
druid-spring-boot-starter1.2.4
mysql-connector8.0.33
mybatis-plus3.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;
        }
}

优势

  1. MyBatis-Plus是一个基于MyBatis的增强插件,它简化了数据库操作,提高了开发效率。通过简单的配置,就可以快速进行CRUD操作,节省大量时间。
  2. Druid是一个高性能的数据库连接池,它结合了C3P0、DBCP等DB池的优点,同时加入了日志监控。Druid可以很好的监控DB池连接和SQL的执行情况,天生就是针对监控而生的DB连接池。
  3. Spring Boot是一个快速开发框架,它简化了Spring应用的配置和部署过程。通过整合MyBatis-Plus和Druid,可以在Spring Boot项目中轻松实现数据库操作和连接池管理。

应用场景

image-20231110001107612

  1. 企业级应用开发

    在构建大型企业级应用时,需要处理大量数据和复杂的业务逻辑。通过整合MyBatis-Plus和Druid,可以大大提高开发效率,简化数据库操作和连接池管理,从而提高整体的开发效率。

  2. 微服务架构

    在微服务架构中,服务之间需要进行频繁的数据交互。使用Spring Boot整合MyBatis-Plus和Druid作为数据访问层的解决方案,可以有效地解冑这一问题。

  3. 高并发场景

    对于需要处理大量并发请求的系统,例如电商网站、社交网络等,使用Spring Boot整合MyBatis-Plus和Druid可以有效提高数据库访问性能,保证系统的稳定运行。


总结

通过本文的介绍,相信大家已经了解了如何在 Spring Boot 项目中整合 MyBatis-Plus 和 Druid。

Spring Boot整合MyBatis-Plus和Druid可以提高开发效率,提高数据库访问性能,简化配置和管理过程,是现代软件开发中的一种优秀解决方案。

在实际开发过程中,我们可以根据项目需求选择合适的框架和工具进行整合。


源码下载

如果需要完整源码请关注公众号"架构殿堂" ,回复 "SpringBoot+mybatisplus+druid"获得


写在最后

感谢您的支持和鼓励! 😊🙏

如果大家对相关文章感兴趣,可以关注公众号"架构殿堂",会持续更新AIGC,系统架构, 分布式, java, GO, python, 游戏相关 等系列文章,一系列干货随时送达!

csdn-end

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现读写分离可以利用 SpringBootMybatisPlus 和 Druid 进行配置。下面是一个简单的实现过程: 1. 添加 MybatisPlus 和 Druid 的 Maven 依赖。 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 在配置文件中添加 Druid 数据源相关配置。 ```yaml spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: initialSize: 5 maxActive: 10 minIdle: 5 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat,wall,log4j connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 3. 配置 MybatisPlus 的多数据源功能。 ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceType.MASTER.getType(), masterDataSource); targetDataSources.put(DataSourceType.SLAVE.getType(), slaveDataSource); return new DynamicDataSource(masterDataSource, targetDataSources); } } ``` 4. 创建一个 DataSourceHolder 类,用于保存当前线程的数据源类型。 ```java public class DataSourceHolder { private static final ThreadLocal<String> HOLDER = new ThreadLocal<>(); public static String getDataSource() { return HOLDER.get(); } public static void setDataSource(String dataSource) { HOLDER.set(dataSource); } public static void clearDataSource() { HOLDER.remove(); } } ``` 5. 创建一个枚举类型 DataSourceType,用于表示数据源类型。 ```java public enum DataSourceType { MASTER("master"), SLAVE("slave"); private final String type; DataSourceType(String type) { this.type = type; } public String getType() { return type; } } ``` 6. 创建一个 DynamicDataSource 类,继承 AbstractRoutingDataSource,用于动态切换数据源。 ```java public class DynamicDataSource extends AbstractRoutingDataSource { private final Map<Object, Object> targetDataSources; public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultDataSource); this.targetDataSources = targetDataSources; super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected Object determineCurrentLookupKey() { return DataSourceHolder.getDataSource(); } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { this.targetDataSources.putAll(targetDataSources); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } @Override public void addTargetDataSource(Object key, Object dataSource) { this.targetDataSources.put(key, dataSource); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } } ``` 7. 创建一个 AopDataSourceConfig 类,用于配置切面,实现动态切换数据源。 ```java @Configuration public class AopDataSourceConfig { @Bean public DataSourceAspect dataSourceAspect() { return new DataSourceAspect(); } } ``` ```java @Aspect public class DataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.Master) " + "|| execution(* com.example.demo.service..*.select*(..)) " + "|| execution(* com.example.demo.service..*.get*(..)) " + "|| execution(* com.example.demo.service..*.query*(..)) " + "|| execution(* com.example.demo.service..*.find*(..)) " + "|| execution(* com.example.demo.service..*.count*(..))") public void read() { } @Pointcut("execution(* com.example.demo.service..*.insert*(..)) " + "|| execution(* com.example.demo.service..*.update*(..)) " + "|| execution(* com.example.demo.service..*.delete*(..))") public void write() { } @Around("read()") public Object read(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.SLAVE.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } @Around("write()") public Object write(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.MASTER.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } } ``` 8. 在 Service 层的方法上使用 @Master 注解,表示强制使用主库。 ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override @Master public boolean save(User user) { return super.save(user); } } ``` 这样就实现了读写分离功能。需要注意的是,在使用 MybatisPlus 进行 CRUD 操作时,需要使用对应的 Service 方法,例如 selectList、selectPage、insert、updateById、deleteById,而不是直接调用 Mapper 方法。否则,数据源切换将不会生效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

The-Venus

您的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值