目录
一、依赖
二、yml 配置
三、xml 配置
四、config 配置
五、使用
实体类
Mapper.java
Service.java
ServiceImpl.java
Mapper.xml
六、逻辑删除
一、依赖
<!-- springboot3 / mybatis-plus 配置,mybatis使用 3.5.16 版本,避免版本冲突 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.16</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-spring-boot3-starter</artifactId> <version>${mybatis-plus-spring-boot3.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-jsqlparser</artifactId> <version>${mybatis-plus-spring-boot3.version}</version> </dependency><mybatis-plus-spring-boot3.version>3.5.10</mybatis-plus-spring-boot3.version>二、yml 配置
application.yml
# MyBatis配置 #mybatis: # # 搜索指定包别名 # typeAliasesPackage: com.leslie.**.domain # # 配置mapper的扫描,找到所有的mapper.xml映射文件 # mapperLocations: classpath*:mapper/**/*Mapper.xml # # 加载全局的配置文件 # configLocation: classpath:mybatis/mybatis-config.xml # mybatis-plus配置 mybatis-plus: # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapper-locations: classpath*:mapper/**/*Mapper.xml # 搜索指定包别名,多个用【;】分隔 type-aliases-package: com.leslie.**.domain; global-config: #数据库相关配置 db-config: #主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; id-type: AUTO logic-delete-value: 1 # 逻辑删除时,is_delete 为删除的值 logic-not-delete-value: 0 # 逻辑删除时,is_delete 为未删除的值 banner: false #原生配置 configuration: map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志输出 # PageHelper分页插件 pagehelper: helperDialect: mysql supportMethodsArguments: true params: count=countSql三、xml 配置
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 全局参数 --> <settings> <!-- 使全局的映射器启用或禁用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 允许JDBC 支持自动生成主键 --> <setting name="useGeneratedKeys" value="true" /> <!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 --> <setting name="defaultExecutorType" value="SIMPLE" /> <!-- 指定 MyBatis 所用日志的具体实现 --> <setting name="logImpl" value="SLF4J" /> <!-- 使用驼峰命名法转换字段 --> <!-- <setting name="mapUnderscoreToCamelCase" value="true"/> --> </settings> </configuration>四、config 配置
MybatisPlusConfig.java
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * Mybatis Plus 配置 */ @EnableTransactionManagement(proxyTargetClass = true) @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 interceptor.addInnerInterceptor(paginationInnerInterceptor()); // 乐观锁插件 interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor()); // 阻断插件 interceptor.addInnerInterceptor(blockAttackInnerInterceptor()); return interceptor; } /** * 分页插件,自动识别数据库类型 <a href="https://baomidou.com/guide/interceptor-pagination.html">...</a> */ public PaginationInnerInterceptor paginationInnerInterceptor() { PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); // 设置数据库类型为mysql paginationInnerInterceptor.setDbType(DbType.MYSQL); // 设置最大单页限制数量,默认 500 条,-1 不受限制 paginationInnerInterceptor.setMaxLimit(-1L); return paginationInnerInterceptor; } /** * 乐观锁插件 <a href="https://baomidou.com/guide/interceptor-optimistic-locker.html">...</a> */ public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() { return new OptimisticLockerInnerInterceptor(); } /** * 如果是对全表的删除或更新操作,就会终止该操作 <a href="https://baomidou.com/guide/interceptor-block-attack.html">...</a> */ public BlockAttackInnerInterceptor blockAttackInnerInterceptor() { return new BlockAttackInnerInterceptor(); } }五、使用
实体类
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; import com.alibaba.excel.annotation.ExcelProperty; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serial; import java.io.Serializable; import java.time.LocalDate; /** * @author Leslie Lee * @version 2003/04/01 * @date 1956/09/12 */ @Data @TableName("test") @ExcelIgnoreUnannotated public class TestEntity implements Serializable { @Serial private static final long serialVersionUID = 1L; // @TableId(type = IdType.AUTO) private Integer id; @ExcelProperty("姓名") private String name; @ExcelProperty("性别") private String sex; private LocalDate createTime; private LocalDate updateTime; @TableLogic private Integer isDelete; }@TableName("表名"):当实体类名与数据库表名不一致时,需用此注解来标明对应的表
@TableId(type = IdType.AUTO):如果 id 为自增,可用此注解进行标识
Mapper.java
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.leslie.ai.domain.TestEntity; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * Mapper 测试 * * @author Leslie Lee * @TIME 1956/09/12 * @Version 2003/04/01 */ @Mapper public interface TestEntityMapper extends BaseMapper<TestEntity> { List<TestEntity> queryTestEntityList(TestEntity o); }@Mapper:动态代理,与 Mapper.xml 对应
extends BaseMapper<实体类>:提供基本的增删改查方法
Service.java
里面的方法需与 Mapper.java 中对应,deleteById 方法实现是用的自带的删除方法,所以不对应也不影响,但是需要重写 sql 语句的方法都要对应
import com.leslie.ai.domain.TestEntity; import java.util.List; /** * Service * * @author Leslie Lee * @TIME 1956/09/12 * @Version 2003/04/01 */ public interface TestEntityService { List<TestEntity> queryTestEntityList(TestEntity o); int deleteById(Integer id); }ServiceImpl.java
直接使用 this.baseMapper 可以拿到Mapper.java 中对应的方法
import com.leslie.ai.domain.TestEntity; import com.leslie.ai.mapper.TestEntityMapper; import com.leslie.ai.service.TestEntityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import java.util.List; /** * ServiceImpl * * @author Leslie Lee * @TIME 1956/09/12 * @Version 2003/04/01 */ @Service public class TestEntityServiceImpl extends ServiceImpl<TestEntityMapper, TestEntity> implements TestEntityService { @Override public List<TestEntity> queryTestEntityList(TestEntity o) { return this.baseMapper.queryTestEntityList(o); } @Override public int deleteById(Integer id) { return this.baseMapper.deleteById(id); } }Mapper.xml
此类文件放在 resources 文件夹下,建议文件路径与实体类一致
namespace:对应实体类全路径
resultMap:方法返回参数,实体类使用表字段名驼峰命名时,不需要再写字段对应关系
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.leslie.ai.mapper.TestEntityMapper"> <!-- 实体类 --> <resultMap type="TestEntity" id="TestEntityResult"> <!-- <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>--> </resultMap> <!-- sql语句 --> <sql id="selectTestEntityList"> </sql> <!-- 方法 --> <select id="queryTestEntityList" parameterType="TestEntity" resultMap="TestEntityResult"> <include refid="selectTestEntityList"/> <where> <if test="fieldName != null and fieldName != ''"> and tableFieldName like concat('%', #{fieldName}, '%')</if> <if test="startDate != null and startDate != ''">and applicationDate >= #{startDate}</if> <if test="endDate != null and endDate != ''">and applicationDate <= #{endDate}</if> </where> </select> </mapper>六、逻辑删除
通过更改表的某一字段状态,区分是否删除
实体类
实体类增加字段:isDelete ===> 对应表字段 is_delete (也可以用其他字段,对应就行)
添加注解:@TableLogic
@TableLogic private Integer isDelete;还可以添加两个字段:创建时间、修改时间
private LocalDate createTime; // create_time private LocalDate updateTime; // update_timeyml 配置
logic-delete-value: 1 # 逻辑删除时,is_delete 为删除的值 logic-not-delete-value: 0 # 逻辑删除时,is_delete 为未删除的值数据库
创建时间、修改时间,字段名就用下面的两个,
然后设置默认值CURRENT_TIMESTAMP(2)
修改时间会在表数据变动时自动更新
Leslie Lee 随笔