MybatisPlus使用

未分类 289 字 发布于 2026-04-04 最后更新于 2026-04-04


✅ 一、标准三层结构(MP 官方推荐)

假设你的实体是:

TrainTransVolMonDetailEntity

1️⃣ Dao 层(Mapper)

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TrainTransVolMonDetailDao
        extends BaseMapper<TrainTransVolMonDetailEntity> {

    // 你自己的自定义SQL可以写这里
}

✔ 继承 BaseMapper<T>​
✔ 自动拥有:

  • insert
  • deleteById
  • updateById
  • selectById
  • selectList
  • selectPage

不用写 XML 也能用


2️⃣ Service 接口

import com.baomidou.mybatisplus.extension.service.IService;

public interface TrainTransVolMonDetailService
        extends IService<TrainTransVolMonDetailEntity> {

    // 你自定义的方法写这里
}

✔ 继承 IService<T>​
✔ 自动拥有:

  • save
  • saveBatch
  • removeById
  • updateById
  • list
  • page
  • getById

3️⃣ ServiceImpl

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class TrainTransVolMonDetailServiceImpl
        extends ServiceImpl<TrainTransVolMonDetailDao, TrainTransVolMonDetailEntity>
        implements TrainTransVolMonDetailService {

    // 自定义方法写这里
}

✔ 继承:

ServiceImpl<Mapper, Entity>

✔ 自动注入 mapper
✔ 自动拥有 saveBatch 等方法


🎯 结构总结

继承谁
DaoBaseMapper
ServiceIService
ServiceImplServiceImpl<Dao, Entity>

🚀 这样你就可以直接用

批量插入(不用写 XML)

this.saveBatch(list, 1000);

普通插入

this.save(entity);

根据条件查询

this.list(
    new QueryWrapper<TrainTransVolMonDetailEntity>()
        .ge("end_date", startTime)
        .lt("end_date", endTime)
        .like("shdw", shdw)
);

⚠️ 常见错误

❌ Dao 不加 @Mapper

会报找不到 Bean

❌ ServiceImpl 不加 @Service

Spring 不会扫描

❌ 继承写反

一定是:

ServiceImpl<Mapper, Entity>

不是反过来

最后更新于 2026-04-04