直接继承basemapper即可获得17个通用crud方法,如insert、deletebyid、updatebyid、selectbyid等,无需写sql和实现类;配合iservice可进一步简化service层开发。

直接让 DAO 接口继承 BaseMapper
继承 BaseMapper 的核心写法
你的 Mapper 接口只需一行声明,泛型填入对应实体类即可:
- public interface UserMapper extends BaseMapper
{} - 其中 User 是你定义的实体类(含 @TableName 注解指定表名)
- MyBatis-Plus 在运行时自动解析 User 字段,生成标准 SQL(如 INSERT INTO user …)
- 无需 XML 文件,也无需编写 insert()、selectById() 等方法体
哪些操作能直接用?
继承后立刻可用的方法包括:
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
- 增:insert(entity) —— 插入单条记录
- 删:deleteById(id)、deleteByMap(map)、deleteBatchIds(ids)
- 改:updateById(entity)、update(entity, wrapper) —— 支持条件更新
- 查:selectById(id)、selectBatchIds(ids)、selectList(wrapper)、selectOne(wrapper)
- 还有 count、exists、逻辑删除等扩展能力(需开启全局配置)
配合 IService 实现更完整分层
如果希望 Service 层也复用通用逻辑,可进一步组合使用:
- Service 接口继承 IService
- ServiceImpl 类继承 ServiceImpl
- 这样 service.save()、service.list()、service.page() 等方法也开箱即用
- 自定义业务逻辑仍可在 Service 中补充,不干扰基础能力
注意事项和常见配置
要让 BaseMapper 正常工作,还需确保以下几点:
- 实体类字段命名与数据库列名一致(或用 @TableField 映射)
- 主键字段标注 @TableId(否则 insert 可能失败)
- 启动类加 @MapperScan("xxx.mapper") 扫描包路径
- pom.xml 引入 mybatis-plus-boot-starter(非原生 MyBatis)
- application.yml 中配置 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 查看生成的 SQL
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










