💡 一则也许对你有用的小广告 🏆

欢迎飞飞程序员   ,你将获得:专属的实战项目(已更新的所有会员标识的项目都能学习) / 1v1 提问 / Java 学习路线 / PHP 学习路线 / 学习打卡 / 社群讨论

  • 正在进行中的项目:《FFBlog知识付费博客项目》 正在持续更新中,基于 Spring Boot 3.x + JDK 21...,点击查看 ;
  • 《从零开发:FFBlog知识付费博客项目(全栈开发)》 演示链接: https://ffblog.ffcxy.com/  ;

截止目前, 飞飞  正在疯狂爆肝实战项目,后续还会上新更多项目,目标是将所学知识开发成项目并且分享给大家,如知识付费系统, Ai系统, CMS系统,在线商城系统,等等 ,欢迎点击围观

SpringBoot框架中的 Mapper

Mapper 不是 SpringBoot 自带组件,是 MyBatis 的概念,SpringBoot 只是整合 MyBatis 来使用 Mapper。 简单一句话:Mapper = 数据访问接口,用来写数据库操作,替代传统 DAO 层

Mapper 就是数据访问层(DAO)的接口,负责把 Java 对象和数据库表之间的增删改查操作对接起来。在 MyBatis-Plus 里,你只需要写一个接口继承 BaseMapper<T>,几乎不用写 SQL,就能直接获得完整的 CRUD 能力。

Mapper 在 MyBatis-Plus 中的定位

三层结构:

Controller(接收请求)
   ↓
Service(业务逻辑,调用 Mapper)
   ↓
Mapper(直接操作数据库表,与 SQL 打交道)

对比传统 MyBatis:要手动写接口 + XML/SQL 映射,一个表就要写一堆方法。而 MyBatis-Plus 的 Mapper 只需继承 BaseMapper<T>,通用增删改查全部内置。

完整使用示例

1. 实体类(对应数据库表 user

@Data
@TableName("user")   // 指定表名
public class User {
    @TableId(type = IdType.AUTO)  // 主键自增
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

2. Mapper 接口 —— 这就是 "Mapper" 本体

@Mapper                       // 方式一:单个标注,让 Spring 扫描到
public interface UserMapper extends BaseMapper<User> {
    // 一个方法都不用写,CRUD 全部继承自 BaseMapper
}

或者在启动类上统一扫描(更常用):

@SpringBootApplication
@MapperScan("com.example.mapper")   // 方式二:扫描整个包
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

3. Service 层调用

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUser(Long id) {
        return userMapper.selectById(id);   // 按主键查
    }

    public List<User> getAdults() {
        // 条件构造器:等价于 SELECT * FROM user WHERE age >= 18
        return userMapper.selectList(
            new LambdaQueryWrapper<User>()
                .ge(User::getAge, 18)
        );
    }

    public int add(User user) {
        return userMapper.insert(user);      // 新增
    }
}

BaseMapper 内置的常用方法

图片

配合 QueryWrapper / LambdaQueryWrapper 可以拼几乎任意 where 条件;复杂 SQL(多表 join、子查询等)仍可像传统 MyBatis 一样,在 Mapper 接口里加自定义方法 + 写 XML。

上一篇 spring-boot-maven-plugin 插件有什么作用?
下一篇 什么是 domain层?domain 层与 DO 对象的关系是啥?

全部评论(0)

头像
😃 😁 😅 😂 😍 😜 😝 🤑 🥵 🥰 😙 😎 😵 😭 😱 😖 🥳 👽 🙈 🤡 😤 💣 💯 💢 ❤️ 👍 👏 👋 👌 🤏 🙏
还没有任何评论哟~