springboot系类代码:springboot-cache-mysql-mybatis

本文深入探讨Spring Boot中缓存的使用与配置,包括@Cacheable、@CachePut、@CacheEvict等注解的应用,以及如何整合Redis作为缓存存储。通过具体的代码示例,展示如何在实际项目中实现高效的数据缓存策略。
  • Cache 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache
  • CacheManager 缓存管理器,管理各种缓存(cache)组件
  • @Cacheable 主要针对方法配置,能够根据方法的请求参数对其进行缓存
  • @CacheEvict 清空缓存
  • @CachePut 保证方法被调用,又希望结果被缓存。与@Cacheable区别在于是否每次都调用方法,常用于更新
  • @EnableCaching 开启基于注解的缓存
  • keyGenerator 缓存数据时key生成策略
  • serialize 缓存数据时value序列化策略
  • @CacheConfig 统一配置本类的缓存注解的属性
package com.programb.trans;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

package com.programb.trans.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.sql.SQLException;


@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {

    private String url;

    private String username;

    private String password;

    private String driverClassName = "com.mysql.cj.jdbc.Driver";

    private Integer initialSize = 10;

    private Integer minIdle = 3;

    private Integer maxActive = 60;

    private Integer maxWait = 60000;

    private Boolean removeAbandoned = true;

    private Integer removeAbandonedTimeout = 180;

    private Integer timeBetweenEvictionRunsMillis = 60000;

    private Integer minEvictableIdleTimeMillis = 300000;

    private String validationQuery = "SELECT 'x'";

    private Boolean testWhileIdle = true;

    private Boolean testOnBorrow = false;

    private Boolean testOnReturn = false;

    private Boolean poolPreparedStatements = true;

    private Integer maxPoolPreparedStatementPerConnectionSize = 50;

    private String filters = "stat";

    public void config(DruidDataSource dataSource) {
        dataSource.setDbType(JdbcConstants.MYSQL);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setInitialSize(initialSize);     
        dataSource.setMinIdle(minIdle);           
        dataSource.setMaxActive(maxActive);    
        dataSource.setMaxWait(maxWait);         
        dataSource.setRemoveAbandoned(removeAbandoned); 
        dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); 
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestOnReturn(testOnReturn);
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getTimeBetweenEvictionRunsMillis() {
        return timeBetweenEvictionRunsMillis;
    }

    public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }

    public Integer getMinEvictableIdleTimeMillis() {
        return minEvictableIdleTimeMillis;
    }

    public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public Boolean getTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(Boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }

    public Boolean getTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(Boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public Boolean getTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(Boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public Boolean getPoolPreparedStatements() {
        return poolPreparedStatements;
    }

    public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
        this.poolPreparedStatements = poolPreparedStatements;
    }

    public Integer getMaxPoolPreparedStatementPerConnectionSize() {
        return maxPoolPreparedStatementPerConnectionSize;
    }

    public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
        this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
    }

    public String getFilters() {
        return filters;
    }

    public void setFilters(String filters) {
        this.filters = filters;
    }

    public Boolean getRemoveAbandoned() {
        return removeAbandoned;
    }

    public void setRemoveAbandoned(Boolean removeAbandoned) {
        this.removeAbandoned = removeAbandoned;
    }

    public Integer getRemoveAbandonedTimeout() {
        return removeAbandonedTimeout;
    }

    public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) {
        this.removeAbandonedTimeout = removeAbandonedTimeout;
    }
}
package com.programb.trans.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;


@Configuration
@EnableTransactionManagement(order = 2)
@MapperScan(basePackages = {"com.programb.trans.dao.repository"})
public class MybatisPlusConfig {

    @Resource
    private DruidProperties druidProperties;
    @Bean
    public DruidDataSource singleDatasource() {
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        return dataSource;
    }
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

package com.programb.trans.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Configuration
@EnableCaching
public class RedisCacheConfig {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();
        redisConf.setHostName(env.getProperty("spring.redis.host"));
        redisConf.setPort(Integer.parseInt(env.getProperty("spring.redis.port")));
        redisConf.setPassword(RedisPassword.of(env.getProperty("spring.redis.password")));
        return new LettuceConnectionFactory(redisConf);
    }

    @Bean
    public RedisCacheConfiguration cacheConfiguration() {
        RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .disableCachingNullValues();
        return cacheConfig;
    }

    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager rcm = RedisCacheManager.builder(redisConnectionFactory())
                .cacheDefaults(cacheConfiguration())
                .transactionAware()
                .build();
        return rcm;
    }

 
    @Bean(name = "KeyGenerator")
    public KeyGenerator myKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... params) {
                logger.info("programb" + Arrays.toString(params));
                return params[0];
            }
        };
    }
}

package com.programb.trans.dao.entity;

import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;

import java.io.Serializable;

@TableName(value = "t_user")
public class User extends Model<User> {

    @TableId(value="id", type= IdType.INPUT)
    private Integer id;

    private String username;

    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    protected Serializable pkVal() {
        return this.id;
    }
}

package com.programb.trans.dao.repository;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.programb.trans.dao.entity.User;

public interface UserMapper extends BaseMapper<User> {
}

package com.programb.trans.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.programb.trans.dao.entity.User;
import com.programb.trans.dao.repository.UserMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class UserService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private UserMapper userMapper;


    @Cacheable(value = "userCache", key = "#id", unless="#result == null")
    public User getById(int id) {
        logger.info("获取用户start...");
        return userMapper.selectById(id);
    }

    @Cacheable(value = "allUsersCache", unless = "#result.size() == 0")
    public List<User> getAllUsers() {
        logger.info("获取所有用户列表");
        return userMapper.selectList(null);
    }


    @Caching(
            put = {@CachePut(value = "userCache", key = "#user.id")},
            evict = {@CacheEvict(value = "allUsersCache", allEntries = true)}
    )
    public User createUser(User user) {
        logger.info("创建用户start..., user.id=" + user.getId());
        userMapper.insert(user);
        return user;
    }


    @Caching(
            put = {@CachePut(value = "userCache", key = "#user.id")},
            evict = {@CacheEvict(value = "allUsersCache", allEntries = true)}
    )
    public User updateUser(User user) {
        logger.info("更新用户start...");
        userMapper.updateById(user);
        return user;
    }

    @Caching(
            evict = {
                    @CacheEvict(value = "userCache", key = "#id"),
                    @CacheEvict(value = "allUsersCache", allEntries = true)
            }
    )
    public void deleteById(int id) {
        logger.info("删除用户start...");
        userMapper.deleteById(id);
    }

}


server.port: 8092


spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456


mybatis-plus:
  mapper-locations: classpath*:com/programb/trans/dao/repository/mapping/*.xml
  typeAliasesPackage: >
    com.xncoding.trans.dao.entity
  global-config:
    id-type: 0 
    db-column-underline: false
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true 
    lazyLoadingEnabled: true 
    multipleResultSetsEnabled: true 

logging:
  level:
    org.springframework.web.servlet: ERROR


spring:
  profiles: dev
  cache:
    type: REDIS
    redis:
      cache-null-values: false
      time-to-live: 600000ms
      use-key-prefix: true
    cache-names: userCache,allUsersCache
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0
    lettuce:
      shutdown-timeout: 200ms
      pool:
        max-active: 7
        max-idle: 7
        min-idle: 2
        max-wait: -1ms

logging:
  level:
    ROOT: INFO
    com:
      xncoding: DEBUG
  file: D:/programb/logs/springboot-cache.log


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.programb</groupId>
    <artifactId>springboot-cache</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-cache</name>
    <description>SpringBoot Transaction</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
		<druid.version>1.1.2</druid.version>
        <mysql-connector.version>8.0.7-dmr</mysql-connector.version>
        <mybatis-plus.version>2.1.8</mybatis-plus.version>
        <mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>com.vaadin.external.google</groupId>
                    <artifactId>android-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- MyBatis plus增强和springboot的集成-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>${mybatisplus-spring-boot-starter.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                </executions>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

<think>我们正在配置MyBatis-Plus,需要设置`mapper-locations`和`global-config`参数。这两个参数分别用于指定Mapper XML文件的位置和全局配置。 根据引用[1]和引用[2]中的信息,我们可以这样配置: 1. **mapper-locations**:用于指定MyBatis Mapper XML文件的位置。在Spring Boot项目中,我们通常在application.yml(或application.properties)中进行配置。 2. **global-config**:用于设置MyBatis-Plus的全局配置,例如表前缀、主键生成策略等。 下面是一个配置示例(以application.yml为例): ```yaml mybatis-plus: # 配置Mapper XML文件的位置 mapper-locations: classpath*:mapper/**/*.xml global-config: # 全局配置设置 db-config: # 全局表前缀 table-prefix: tbl_ # 全局主键型 id-type: auto ``` 解释: - `mapper-locations: classpath*:mapper/**/*.xml`:表示在classpath路径下(包括jar文件内)的所有mapper目录及其子目录中查找所有以.xml结尾的文件作为Mapper XML文件。 - `global-config.db-config.table-prefix: tbl_`:设置全局表前缀为`tbl_`,这样在实体上不需要使用`@TableName`指定表名时,会自动将实体名转换为小写并在前面加上`tbl_`作为表名。例如,实体`User`对应的表名是`tbl_user`。 - `global-config.db-config.id-type: auto`:设置主键生成策略为数据库自增(如MySQL的AUTO_INCREMENT)。 另外,引用[3]提醒我们,在配置中如果使用占位符(如`${...}`),需要确保该占位符在配置文件中已经定义,并且注意配置文件加载顺序。但在这个配置中,我们没有使用占位符,所以不用担心。 如果使用application.properties配置,则如下: ```properties # Mapper XML文件位置 mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml # 全局配置 mybatis-plus.global-config.db-config.table-prefix=tbl_ mybatis-plus.global-config.db-config.id-type=auto ``` 注意:在配置`id-type`时,常用的值有: - `auto`:数据库自增 - `none`:无状态,该型为未设置主键型(跟随全局) - `input`:用户输入ID - `assign_id`:分配ID(主键型为Number(Long和Integer)或String),使用接口`IdentifierGenerator`的方法`nextId`(默认实现为`DefaultIdentifierGenerator`雪花算法) - `assign_uuid`:分配UUID(主键型为String) 请根据实际需求选择。 最后,确保你的Mapper接口被正确扫描,通常使用`@MapperScan`注解在启动上指定Mapper接口所在的包,例如: ```java @SpringBootApplication @MapperScan("com.example.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,MyBatis-Plus就能找到Mapper接口和对应的XML文件,并应用全局配置。 §§相关问题§§ 1. MyBatis-Plus中如何配置多个mapper-locations路径? 2. global-config除了表前缀和主键型,还有哪些常用配置? 3. 如何为不同的表设置不同的主键生成策略? 4. 在MyBatis-Plus中,如何自定义ID生成器?</think>### MyBatis-Plus 配置参数详解 #### 1. **mapper-locations 参数配置** **作用**:指定 MyBatis Mapper XML 文件的路径位置,支持通配符匹配多个文件。 **配置示例**(YAML 格式): ```yaml mybatis-plus: mapper-locations: classpath*:mapper/**/*.xml ``` **说明**: - `classpath*:`:从所有路径(包括依赖的 JAR 包)中搜索 - `mapper/**/*.xml`:匹配 `mapper` 目录下所有子目录的 `.xml` 文件 - 支持多个路径,用逗号分隔(如:`classpath:mapper1/*.xml, classpath:mapper2/*.xml`) #### 2. **global-config 参数配置** **作用**:配置全局策略,包含数据库表前缀、主键生成策略等。 **配置示例**(YAML 格式): ```yaml mybatis-plus: global-config: db-config: table-prefix: tbl_ # 全局表前缀 id-type: auto # 主键策略(auto: 数据库自增) logic-delete-field: deleted # 逻辑删除字段名 logic-delete-value: 1 # 删除状态值 logic-not-delete-value: 0 # 未删除状态值 ``` **关键子配置说明**: | 参数 | 说明 | 可选值 | |------------------------|----------------------------------------------------------------------|---------------------------------| | `table-prefix` | 自动给所有表名添加前缀(如 `user` → `tbl_user`) | 任意字符串 | | `id-type` | 主键生成策略 | `auto`(自增),`assign_id`(雪花ID)| | `logic-delete-field` | 逻辑删除字段名(需在表中存在) | 如 `is_deleted` | | `logic-delete-value` | 删除状态值 | 数字/字符串 | | `logic-not-delete-value`| 未删除状态值 | 数字/字符串 | #### 3. **完整配置示例** ```yaml mybatis-plus: mapper-locations: classpath*:com/example/mapper/**/*.xml global-config: db-config: table-prefix: sys_ id-type: assign_id logic-delete-field: is_deleted logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true # 开启驼峰命名转换 ``` #### 4. **注意事项** 1. **路径通配符规则**: - `*` 匹配单层目录 - `**` 匹配多层目录 - 示例:`classpath*:mappers/**/postgresql/*Mapper.xml` 2. **优先级规则**: - 实体注解(如 `@TableName`)> 全局配置 > 数据库表名 - 例如:若实体有 `@TableName("user")`,则忽略全局 `table-prefix` 3. **逻辑删除配置**: ```java @TableLogic private Integer isDeleted; // 需与global-config中的字段名一致 ``` 4. **多模块项目**: ```yaml mapper-locations: - classpath*:module1/mapper/*.xml - classpath*:module2/mapper/**/*.xml ``` [^1]: 关于 MyBatis-Plus 的基本配置路径定义,详见官方文档 [^2]: 全局表前缀配置的实际应用效果示例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值