1 BaseMapper<T>
说明:
- 通用 CRUD 封装 BaseMapper 接口,为
Mybatis-Plus启动时自动解析实体表关系映射转换为Mybatis内部对象注入容器- 泛型
T为任意实体对象- 参数
Serializable为任意类型主键Mybatis-Plus不推荐使用复合主键约定每一张表都有自己的唯一id主键- 对象
Wrapper为条件构造器
MyBatis-Plus 中的基本 CRUD 在内置的 BaseMapper 中都已得到了实现,因此我们继承该接口以后可以直接使用。
BaseMapper 中提供的 CRUD 方法:
-
增加:Insert
// 插入一条记录 int insert(T entity); -
删除:Delete
// 根据 entity 条件,删除记录 int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper); // 删除(根据 ID 批量删除) int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); // 根据 ID 删除 int deleteById(Serializable id); // 根据 columnMap 条件,删除记录 int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); -
修改:Update
// 根据 whereWrapper 条件,更新记录 int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper); // 根据 ID 修改 int updateById(@Param(Constants.ENTITY) T entity); -
查询:Selete
// 根据 ID 查询 T selectById(Serializable id); // 根据 entity 条件,查询一条记录 T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 查询(根据ID 批量查询) List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); // 根据 entity 条件,查询全部记录 List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 查询(根据 columnMap 条件) List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); // 根据 Wrapper 条件,查询全部记录 List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值 List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根据 entity 条件,查询全部记录(并翻页) IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根据 Wrapper 条件,查询全部记录(并翻页) IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根据 Wrapper 条件,查询总记录数 Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
2 调用 Mapper 层实现 CRUD
2.1 插入
调用方法:int deleteById(Serializable id);
最终执行的结果,所获取的 id 为 1527206783590903810
这是因为 MyBatis-Plus 在实现插入数据时,会默认基于雪花算法的策略生成 id
@Test
public void testInsert(){
User user = new User();
user.setName("Vz");
user.setAge(21);
user.setEmail("vz@oz6.cn");
int result = userMapper.insert(user);
System.out.println(result > 0 ? "添加成功!" : "添加失败!");
System.out.println("id自动获取" + user.getId());
}2.2 删除
2.2.1 根据 ID 删除数据
调用方法:int deleteById(Serializable id);
@Test
public void testDeleteById(){
int result = userMapper.deleteById(1527206783590903810L);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}2.2.2 根据 ID 批量删除数据
调用方法:int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@Test
public void testDeleteBatchIds(){
List<Long> ids = Arrays.asList(6L,7L,8L);
int result = userMapper.deleteBatchIds(ids);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}2.2.3 根据 Map 条件删除数据
调用方法:int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
@Test
public void testDeleteByMap(){
//执行 SQL 为:DELETE FROM user WHERE name = ? AND age = ?
Map<String,Object> map = new HashMap<>();
map.put("name","Vz");
map.put("age",21);
int result = userMapper.deleteByMap(map);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}2.3 修改
调用方法:int updateById(@Param(Constants.ENTITY) T entity);
@Test
public void testUpdateById(){
//执行 SQL 为: UPDATE user SET name=?, age=?, email=? WHERE id=?
User user = new User();
user.setId(6L);
user.setName("VzUpdate");
user.setAge(18);
user.setEmail(" Vz@sina.com ");
int result = userMapper.updateById(user);
System.out.println(result > 0 ? "修改成功!" : "修改失败!");
System.out.println("受影响的行数为:" + result);
}2.4 查询
2.4.1 根据 ID 查询用户信息
调用方法:T selectById(Serializable id);
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}2.4.2 根据多个 ID 查询多个用户信息
调用方法:List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@Test
public void testSelectBatchIds(){
//执行 SQL 为:SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
List<Long> ids = Arrays.asList(1L,2L,3L);
List<User> users = userMapper.selectBatchIds(ids);
users.forEach(System.out::println);
}2.4.3 根据 Map 条件查询用户信息
调用方法:List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
@Test
public void testSelectByMap(){
//执行 SQL 为:SELECT id,name,age,email FROM user WHERE age = ?
Map<String,Object> map = new HashMap<>();
map.put("age",18);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}2.4.4 查询所有用户信息
调用方法:List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@Test
void testSelectList(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}3 通用 Service
说明:
- 通用 Service CRUD 封装
IService接口,进一步封装 CRUD 采用get 查询单行、remove 删除、list 查询集合、page 分页前缀命名方式区分Mapper层避免混淆,- 泛型
T为任意实体对象- 建议如果存在自定义通用 Service 方法的可能,请创建自己的
IBaseService继承Mybatis-Plus提供的基类- 对象
Wrapper为条件构造器
MyBatis-Plus 中有一个接口 IService 和其实现类 ServiceImpl,封装了常见的业务层逻辑,详情查看源码 IService 和 ServiceImpl。
使用时:
- 首先,创建自定义 Service 接口,继承 IService 接口
- 其次,创建自定义 Service 实现类,继承 ServiceImpl 实现类
因此我们在使用的时候仅需在自己定义的 Service 接口中继承 IService 接口,在自己的实现类中实现自己的 Service 并继承 ServiceImpl 即可。
IService 中的 CRUD 方法
-
增加:Save、SaveOrUpdate
// 插入一条记录(选择字段,策略插入) boolean save(T entity); // 插入(批量) boolean saveBatch(Collection<T> entityList); // 插入(批量) boolean saveBatch(Collection<T> entityList, int batchSize); // TableId 注解存在更新记录,否插入一条记录 boolean saveOrUpdate(T entity); // 根据 updateWrapper 尝试更新,否继续执行 saveOrUpdate(T)方法 boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper); // 批量修改插入 boolean saveOrUpdateBatch(Collection<T> entityList); // 批量修改插入 boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize); -
删除:Remove
// 根据 entity 条件,删除记录 boolean remove(Wrapper<T> queryWrapper); // 根据 ID 删除 boolean removeById(Serializable id); // 根据 columnMap 条件,删除记录 boolean removeByMap(Map<String, Object> columnMap); // 删除(根据 ID 批量删除) boolean removeByIds(Collection<? extends Serializable> idList); -
修改:Update
// 根据 UpdateWrapper 条件,更新记录需要设置 sqlset boolean update(Wrapper<T> updateWrapper); // 根据 whereWrapper 条件,更新记录 boolean update(T updateEntity, Wrapper<T> whereWrapper); // 根据 ID 选择修改 boolean updateById(T entity); // 根据 ID 批量更新 boolean updateBatchById(Collection<T> entityList); // 根据 ID 批量更新 boolean updateBatchById(Collection<T> entityList, int batchSize); -
查询:Get、List、Count
// 根据 ID 查询 T getById(Serializable id); // 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1") T getOne(Wrapper<T> queryWrapper); // 根据 Wrapper,查询一条记录 T getOne(Wrapper<T> queryWrapper, boolean throwEx); // 根据 Wrapper,查询一条记录 Map<String, Object> getMap(Wrapper<T> queryWrapper); // 根据 Wrapper,查询一条记录 <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); // 查询所有 List<T> list(); // 查询列表 List<T> list(Wrapper<T> queryWrapper); // 查询(根据 ID 批量查询) Collection<T> listByIds(Collection<? extends Serializable> idList); // 查询(根据 columnMap 条件) Collection<T> listByMap(Map<String, Object> columnMap); // 查询所有列表 List<Map<String, Object>> listMaps(); // 查询列表 List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper); // 查询全部记录 List<Object> listObjs(); // 查询全部记录 <V> List<V> listObjs(Function<? super Object, V> mapper); // 根据 Wrapper 条件,查询全部记录 List<Object> listObjs(Wrapper<T> queryWrapper); // 根据 Wrapper 条件,查询全部记录 <V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); // 查询总记录数 int count(); // 根据 Wrapper 条件,查询总记录数 int count(Wrapper<T> queryWrapper); -
分页:Page
// 根据 ID 查询 T getById(Serializable id); // 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1") T getOne(Wrapper<T> queryWrapper); // 根据 Wrapper,查询一条记录 T getOne(Wrapper<T> queryWrapper, boolean throwEx); // 根据 Wrapper,查询一条记录 Map<String, Object> getMap(Wrapper<T> queryWrapper); // 根据 Wrapper,查询一条记录 <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
4 调用 Service 层操作数据
我们在自己的 Service 接口中通过继承 MyBatis-Plus 提供的 IService 接口,不仅可以获得其提供的 CRUD 方法,而且还可以使用自身定义的方法。
-
创建
UserService并继承IServicepublic interface UserService extends IService<User> {} -
创建
UserService的实现类并继承ServiceImpl@Service public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{} -
测试查询记录数
调用方法:int count();
@Autowired private UserService userService; @Test public void testGetCount(){ long count = userService.count(); System.out.println("总记录数:" + count); } -
测试批量插入数据
调用方法:boolean saveBatch(Collection<T> entityList);
@Test public void test(){ List<User> list = new ArrayList<>(); for (int i = 1; i <= 10; i++) { User user = new User(); user.setName("Vz"+i); user.setAge(20+i); list.add(user); } boolean b = userService.saveBatch(list); System.out.println(b ? "添加成功!" : "添加失败!"); }