小瓶毒药 發表於 2026-4-6 11:57:00

MyBatis-Plus实战:Spring Boot数据库操作效率提升10倍

<h2>前言</h2>
<p>MyBatis-Plus(MP)是 MyBatis 的增强工具,无需编写 SQL 即可完成 CRUD 操作,极大提升开发效率。本文带你实战 Spring Boot 整合 MyBatis-Plus。</p>
<h2>一、引入依赖</h2>
<pre><code>&lt;!-- pom.xml --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.baomidou&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-plus-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;3.5.5&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;mysql&lt;/groupId&gt;
    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
&lt;/dependency&gt;

# application.yml
spring:
datasource:
    url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
    db-config:
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0</code></pre>
<h2>二、实体类</h2>
<pre><code>@Data
@TableName("user")
public class User {

    @TableId(type = IdType.AUTO)
    private Long id;

    @TableField("username")
    private String username;

    private String email;

    private Integer age;

    @TableLogic// 逻辑删除
    private Integer deleted;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
}</code></pre>
<h2>三、Mapper 接口</h2>
<pre><code>@Mapper
public interface UserMapper extends BaseMapper&lt;User&gt; {
    // 继承 BaseMapper 后,自动拥有以下方法:
    // - insert(entity)
    // - deleteById(id)
    // - updateById(entity)
    // - selectById(id)
    // - selectList(wrapper)
    // - selectPage(page, wrapper)
    // 无需编写 XML!
}</code></pre>
<h2>四、条件构造器</h2>
<pre><code>// 查询年龄大于18且邮箱不为空的用户
List&lt;User&gt; users = userMapper.selectList(
    new LambdaQueryWrapper&lt;User&gt;()
      .gt(User::getAge, 18)
      .isNotNull(User::getEmail)
      .orderByDesc(User::getCreateTime)
);

// 模糊查询
List&lt;User&gt; users = userMapper.selectList(
    new LambdaQueryWrapper&lt;User&gt;()
      .likeRight(User::getUsername, "张")
      .between(User::getAge, 20, 30)
);

// 更新:年龄大于30的用户状态改为1
userMapper.update(null,
    new LambdaUpdateWrapper&lt;User&gt;()
      .set(User::getStatus, 1)
      .gt(User::getAge, 30)
);</code></pre>
<h2>五、分页查询</h2>
<pre><code>// 分页配置类
@Configuration
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
      MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
      interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
      return interceptor;
    }
}

// 分页查询
Page&lt;User&gt; page = new Page&lt;&gt;(1, 10);// 第1页,每页10条
userMapper.selectPage(page,
    new LambdaQueryWrapper&lt;User&gt;()
      .gt(User::getAge, 18)
);

List&lt;User&gt; records = page.getRecords();// 当前页数据
long total = page.getTotal();         // 总记录数
long pages = page.getPages();         // 总页数</code></pre>
<h2>六、代码生成器</h2>
<pre><code>// AutoGenerator 一键生成 Entity、Mapper、Service、Controller
AutoGenerator generator = new AutoGenerator();

// 全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
globalConfig.setAuthor("myname");
globalConfig.setOpen(false);
generator.setGlobalConfig(globalConfig);

// 数据源配置
DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder(
    "jdbc:mysql://localhost:3306/mydb",
    "root", "123456"
).build();
generator.setDataSource(dataSourceConfig);

// 策略配置
StrategyConfig strategyConfig = new StrategyConfig.Builder()
    .addInclude("user", "order")// 表名
    .entityBuilder().enableLombok()
    .controllerBuilder().enableRestStyle()
    .build();
generator.setStrategy(strategyConfig);

generator.execute();</code></pre>
<h2>总结</h2>
<p>MyBatis-Plus 让数据库操作变得简单高效。核心要点:BaseMapper 提供开箱即用的 CRUD、LambdaWrapper 类型安全的条件构造、内置分页插件、代码生成器大幅提升效率。</p>
<p>觉得有帮助请点赞收藏!有问题欢迎评论区交流 🚀</p>

</div>
<div id="MySignature" role="contentinfo">
   

---

📌 **如果觉得文章对你有帮助,欢迎点赞👍收藏⭐!**

💬 有问题或建议?欢迎在评论区留言讨论~

🔗 更多技术干货请关注作者:弥烟袅绕

📚 本文地址:https://www.cnblogs.com/czlws/p/19825834/mybatis-plus-spring-boot-database-crud<br><br>
来源:https://www.cnblogs.com/czlws/p/19825834/mybatis-plus-spring-boot-database-crud
頁: [1]
查看完整版本: MyBatis-Plus实战:Spring Boot数据库操作效率提升10倍