Mybatis-flex配置全局参数

第一次使用springboot整合mybatis-flex,想配置一下常规配置比如不打印banner,修改数据库的方言(默认是mysql),开启或关闭二级缓存(默认开启),不打印sql日志等等,然后在application.yaml中配置都不起作用,最后看了一下源码 ,可以在使用@Configuration配置,现在记录一下:

package com.chhuang.web.config;

import com.chhuang.core.config.UUIDKeyGenerator;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.keygen.KeyGeneratorFactory;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @Description MyBatisFlex配置 注册自定义主键 审计 缓存 SQL日志打印
 * @Author Darren Huang
 * @Date 2023-05-11 8:37
 */
@Configuration
public class MyBatisFlexConfiguration implements ConfigurationCustomizer {
    private static final Logger logger = LoggerFactory.getLogger("mybatis-flex-sql");

    public MyBatisFlexConfiguration() {
        //配置mybatis-flex全局配置
        FlexGlobalConfig defaultConfig = FlexGlobalConfig.getDefaultConfig();
        defaultConfig.setPrintBanner(false);//不打印banner
        defaultConfig.setDbType(DbType.POSTGRE_SQL);//数据库方言

        //注册自定义主键
        KeyGeneratorFactory.register("uuid", new UUIDKeyGenerator());

        //开启审计功能
        AuditManager.setAuditEnable(true);

        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage ->
                logger.info("{},{}ms", auditMessage.getFullSql(), auditMessage.getElapsedTime())
        );
    }

    /**
     * 自定义的FlexConfiguration配置
     * @param flexConfiguration
     */
    @Override
    public void customize(FlexConfiguration flexConfiguration) {
//        flexConfiguration.setCacheEnabled(false);//开启或关闭mybatis二级缓存
//        flexConfiguration.setLogImpl(NoLoggingImpl.class);//是否打印sql日志 StdOutImpl.class打印日志  NoLoggingImpl.class不打日志
    }
}

解释一下,FlexGlobalConfig是全局的配置参数,可以通过获取默认配置参数来修改FlexGlobalConfig.getDefaultConfig()。

FlexConfiguration的配置参数可以通过实现ConfigurationCustomizer接口的customize()自定义方法来修改。

然后还配置了数据库主键id的uuid方法,默认KeyType没有uuid的功能,要自己写。然后就是开启审计可以打印出sql执行了多少时间。

其实配置请大家自己参考源码,官网文档有点少,而且也不是很新。

另外官网上表示写好一个account实体类会自动生成一个ACCOUNT类直接用,其实生成的ACCOUNT是在Table类中,要用Table.ACCOUNT才能用,还是看源码比文档正确。

Flex很不错,加油

<think>由于问题涉及企业级配置,我将从MyBatis-Flex配置、使用以及企业级应用中的常见实践进行说明。 注意:MyBatis-Flex 是一个轻量级、易于使用的MyBatis增强框架,它提供了很多强大的功能,如分页、多表查询、逻辑删除等。 企业级配置通常包括: 1. 数据源配置(支持多数据源) 2. 事务管理 3. 分页插件配置 4. 逻辑删除配置 5. 自动填充(如自动填充创建时间、更新时间等) 6. 多租户配置(如果需要) 7. SQL打印(用于调试) 下面是一个基于Spring BootMyBatis-Flex企业级配置示例。 步骤1:添加依赖 在pom.xml中添加MyBatis-FlexSpring Boot的依赖。 步骤2:配置数据源 在application.yml中配置数据源。 步骤3:配置MyBatis-Flex 创建配置类,配置分页插件、逻辑删除、多租户等。 步骤4:定义实体类和Mapper接口 使用MyBatis-Flex的注解定义实体类,并创建Mapper接口。 步骤5:编写Service和Controller(根据需求) 下面我们详细展开: 1. 添加依赖(pom.xml): 注意:这里使用Spring Boot 3.x版本,如果使用2.x版本,请调整依赖版本。 ```xml <dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Flex Spring Boot Starter --> <dependency> <groupId>com.mybatis-flex</groupId> <artifactId>mybatis-flex-spring-boot-starter</artifactId> <version>1.0.0</version> <!-- 请使用最新版本 --> </dependency> <!-- 数据库驱动,这里使用MySQL --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <!-- Lombok(可选) --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> ``` 2. 配置数据源(application.yml): ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver # MyBatis-Flex 配置 mybatis-flex: # 打印SQL日志 print-sql: true # 配置逻辑删除 global-config: logic-delete: # 逻辑删除字段名 column: is_deleted # 删除时的值 logicDeleteValue: 1 # 未删除时的值 logicNotDeleteValue: 0 # 自动填充配置 insert-update-fill: # 创建时间 createTime: onInsert: true value: now() # 或者使用数据库函数,如:CURRENT_TIMESTAMP # 更新时间 updateTime: onUpdate: true value: now() # 多租户配置(如果需要) # tenant-config: # column: tenant_id # ignore-tables: tenant_table1, tenant_table2 ``` 3. 配置分页插件(如果需要自定义分页参数): 在Spring Boot中,MyBatis-Flex已经自动配置了分页插件,如果需要自定义,可以创建一个配置类: ```java @Configuration public class MyBatisFlexConfig { /** * 配置分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // 设置分页类型为 PageHelper 风格 paginationInterceptor.setDbType(DbType.MYSQL); return paginationInterceptor; } } ``` 4. 实体类示例(使用注解): ```java @Table("tb_account") public class Account { @Id(keyType = KeyType.Auto) private Long id; private String userName; private Integer age; // 逻辑删除字段 @Column(isLogicDelete = true) private Integer isDeleted; // 自动填充字段 @Column(onInsertValue = "now()") private Date createTime; @Column(onUpdateValue = "now()") private Date updateTime; // 省略 getter 和 setter(可以使用Lombok) } ``` 5. Mapper接口: ```java public interface AccountMapper extends BaseMapper<Account> { // 可以定义自定义方法 } ``` 6. Service层示例: ```java @Service public class AccountService { @Autowired private AccountMapper accountMapper; public Account getById(Long id) { return accountMapper.selectOneById(id); } // 分页查询 public Page<Account> page(Page<Account> page) { QueryWrapper query = QueryWrapper.create() .where(Account::getAge).ge(18) .orderBy(Account::getId.desc()); return accountMapper.paginate(page, query); } } ``` 7. Controller层示例: ```java @RestController @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @GetMapping("/{id}") public Account getAccount(@PathVariable Long id) { return accountService.getById(id); } @GetMapping("/page") public Page<Account> page(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) { Page<Account> page = new Page<>(pageNum, pageSize); return accountService.page(page); } } ``` 8. 多数据源配置(如果需要): 在application.yml中配置多个数据源,并使用@DS注解在Mapper或方法上指定数据源。 首先,添加多数据源依赖(如果使用MyBatis-Flex的多数据源支持): ```xml <dependency> <groupId>com.mybatis-flex</groupId> <artifactId>mybatis-flex-multidatasource</artifactId> <version>1.0.0</version> </dependency> ``` 配置多数据源: ```yaml spring: datasource: master: url: jdbc:mysql://localhost:3306/master?characterEncoding=utf-8&useSSL=false username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver slave: url: jdbc:mysql://localhost:3306/slave?characterEncoding=utf-8&useSSL=false username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver # MyBatis-Flex 多数据源配置 mybatis-flex: datasource: master: type: master datasource-key: master slave: type: slave datasource-key: slave ``` 然后在需要切换数据源的方法或类上使用@DS注解: ```java @Service public class AccountService { @DS("slave") public Account getFromSlave(Long id) { // ... } } ``` 以上是一个基本的MyBatis-Flex企业级配置和实现。在实际项目中,可能还需要考虑缓存、事务管理、异常处理等。 注意:以上代码示例中的部分配置(如自动填充的值)可能需要根据实际数据库进行调整,例如MySQL可以使用`CURRENT_TIMESTAMP`,而H2数据库可能使用`NOW()`。 解释: - 逻辑删除:通过全局配置,指定逻辑删除字段和值,框架会在删除和查询时自动加上条件。 - 自动填充:在插入或更新时自动填充字段值,如创建时间和更新时间。 - 分页插件:MyBatis-Flex内置了分页插件,可以方便地进行分页查询。 - 多数据源:通过配置多个数据源,并使用@DS注解切换。 注意事项: - 确保数据库表字段和实体类属性映射正确。 - 逻辑删除和自动填充的配置需要和数据库表设计一致。 以上配置和代码示例可以帮助你快速搭建一个基于MyBatis-Flex的企业级应用。</think>### MyBatis-Flex 企业级配置及实现指南 MyBatis-Flex 是一个轻量级、高性能的 MyBatis 增强框架,专注于简化 CRUD 操作并支持高级查询功能。以下是企业级项目的完整配置方案: --- #### 1. Maven 依赖配置 ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Flex 核心 --> <dependency> <groupId>com.mybatis-flex</groupId> <artifactId>mybatis-flex-spring-boot-starter</artifactId> <version>1.5.0</version> <!-- 使用最新版本 --> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> </dependencies> ``` --- #### 2. 企业级配置(application.yml) ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/enterprise_db?useSSL=false&serverTimezone=UTC username: admin password: securePass!123 driver-class-name: com.mysql.cj.jdbc.Driver hikari: maximum-pool-size: 20 connection-timeout: 30000 # MyBatis-Flex 高级配置 mybatis-flex: configuration: map-underscore-to-camel-case: true # 自动驼峰转换 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # SQL日志输出 global-config: logic-delete: # 全局逻辑删除配置 column: is_deleted logicNotDeleteValue: 0 logicDeleteValue: 1 key-config: # 主键生成策略 id: keyType: auto value: IdWorker.getIdStr() # 分布式ID生成 insert-update-fill: # 自动填充 createTime: onInsert: true value: now() updateTime: onUpdate: true value: now() ``` --- #### 3. 实体类映射(使用注解) ```java @Table("sys_user") public class User { @Id(keyType = KeyType.Generator, value = "uuid") private String userId; @Column("username") private String name; @Column(ignore = true) // 忽略非表字段 private String temporaryCode; @Column(isLogicDelete = true) // 逻辑删除字段 private Integer isDeleted; @Column(onInsertValue = "now()") // 插入时自动填充 private Date createTime; // Lombok 注解(实际企业项目推荐) // Getter/Setter 省略... } ``` --- #### 4. Mapper 接口(继承增强接口) ```java @Mapper public interface UserMapper extends BaseMapper<User> { // 自定义复杂查询 @Select("SELECT * FROM sys_user WHERE department_id = #{deptId}") List<User> selectByDepartment(@Param("deptId") String deptId); // 条件构造器查询 default List<User> selectAdmins() { QueryWrapper wrapper = QueryWrapper.create() .where(User::getRole).eq("admin") .and(User::getStatus).eq(1); return selectListByQuery(wrapper); } } ``` --- #### 5. Service 层实现(事务控制) ```java @Service public class UserService { @Autowired private UserMapper userMapper; @Transactional public void createUserWithDepartment(User user, String deptId) { // 1. 插入用户 userMapper.insert(user); // 2. 关联部门(演示事务操作) userMapper.insertUserDeptRelation(user.getUserId(), deptId); // 3. 更新部门人数 userMapper.updateDeptUserCount(deptId); } // 逻辑删除示例 public int safeDeleteUser(String userId) { return userMapper.deleteById(userId); // 实际执行的是 UPDATE ... SET is_deleted=1 } } ``` --- #### 6. 多租户实现方案 ```java // 多租户配置类 @Configuration public class TenantConfig implements TenantFactory { @Ov
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值