一、BaseMapper
MyBatis-Plus 中的基本 CRUD 在内置的 BaseMapper 中都已得到了实现,我们可以直接使用,接口的内容如下:
package com.baomidou.mybatisplus.core.mapper;
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据实体(ID)删除
*
* @param entity 实体对象
* @since 3.4.4
*/
int deleteById(T entity);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where
* 语句)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成
* where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/*** 根据 entity 条件,查询一条记录
* <p>查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常
</p>
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
List<T> ts = this.selectList(queryWrapper);
if (CollectionUtils.isNotEmpty(ts)) {
if (ts.size() != 1) {
throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
}
return ts.get(0);
}
return null;
}
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Long selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
<P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER)
Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
二、插入
测试代码如下所示,最终执行的结果,所获取的 id 为 1475754982694199298,这是因为 MyBatis-Plus 在实现插入数据时,会默认基于雪花算法的策略生成 id。
@Test
public void testInsert(){
User user = new User(null, "张三", 23, "zhangsan@atguigu.com");
// INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
int result = userMapper.insert(user);
System.out.println("受影响行数:"+result);
// 1475754982694199298
System.out.println("id自动获取:"+user.getId());
}
三、删除
3.1 通过 id 删除
@Test
public void testDeleteById(){
// DELETE FROM user WHERE id=?
int result = userMapper.deleteById(1475754982694199298L);
System.out.println("受影响行数:"+result);
}
3.2 通过 id 批量删除
@Test
public void testDeleteBatchIds(){
// DELETE FROM user WHERE id IN ( ? , ? , ? )
List<Long> idList = Arrays.asList(1L, 2L, 3L);
int result = userMapper.deleteBatchIds(idList);
System.out.println("受影响行数:"+result);
}
3.3 通过 map 删除
@Test
public void testDeleteByMap(){
// 根据 map 集合中所设置的条件删除记录
// DELETE FROM user WHERE name = ? AND age = ?
Map<String, Object> map = new HashMap<>();
map.put("age", 23);
map.put("name", "张三");
int result = userMapper.deleteByMap(map);
System.out.println("受影响行数:"+result);
}
四、修改
@Test
public void testUpdateById(){
User user = new User(4L, "admin", 22, null);
// UPDATE user SET name=?, age=? WHERE id=?
int result = userMapper.updateById(user);
System.out.println("受影响行数:"+result);
}
五、查询
5.1 根据 id 查询
@Test
public void testSelectById(){
// 根据 id 查询用户信息
// SELECT id,name,age,email FROM user WHERE id=?
User user = userMapper.selectById(4L);
System.out.println(user);
}
5.2 根据多个 id 查询
@Test
public void testSelectBatchIds(){
// 根据多个 id 查询多个用户信息
// SELECT id,name,age,email FROM user WHERE id IN ( ? , ? )
List<Long> idList = Arrays.asList(4L, 5L);
List<User> list = userMapper.selectBatchIds(idList);
list.forEach(System.out::println);
}
5.3 根据 map 查询
@Test
public void testSelectByMap(){
// 通过 map 条件查询用户信息
// SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
Map<String, Object> map = new HashMap<>();
map.put("age", 22);
map.put("name", "admin");
List<User> list = userMapper.selectByMap(map);
list.forEach(System.out::println);
}
5.4 查询所有数据
@Test
public void testSelectList(){
// 查询所有用户信息
// SELECT id,name,age,email FROM user
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}
通过观察 BaseMapper 中的方法,大多方法中都有 Wrapper 类型的形参,此为条件构造器,可针对于 SQL 语句设置不同的条件,若没有条件,则可以为该形参赋值 null,即查询(删除/修改)所有数据。
六、自定义功能
上面是对 BaseMapper 中的方法进行的一些测试,当 BaseMapper 中的方法无法满足我们的需求,它里面的方法可以快速的满足我们单表的增删改查,如果此时我们想要实现多表联查呢?其实只需要和平常的 Mybatis 一样使用即可。即创建映射文件。
我们只需要在配置文件中配置 mapper-locations 标签即可,如下所示,他有个默认值,默认扫描的路径就是 resources 目录下的 mapper 目录下的任意路径的 xml 文件,所以说这个标签完全可以不用写,如果想自定义目录的话才写这个标签
在 resources 目录创建一个 mapper 文件夹,在里面创建一个 UserMapper.xml 文件,内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatisplus.mapper.UserMapper">
<select id="selectMapById" resultType="map">
select id,name,age,email from user where id = #{id}
</select>
</mapper>
在 UserMapper 中创建方法,如下:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mybatisplus.entity.User;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public interface UserMapper extends BaseMapper<User> {
Map<String,Object> selectMapById(Long id);
}
测试代码如下:
@Test
public void testSelectMapById(){
Map<String, Object> map = userMapper.selectMapById(1L);
System.out.println(map);
}
七、通用 Service
7.1 说明
MyBatis-Plus 不光提供了通用的 Mapper(BaseMapper ),还提供了通用的 Service,也就是说我们也可以直接使用通用的 Service 中的方法。
这个通用的 Service 名称为 IService,它进一步封装了 CRUD,即查询单行方法使用 get 前缀、删除方法使用 remove 前缀、查询集合方法使用 list 前缀、分页查询方法使用 page 前缀等,避免与 Mapper 层混淆。
7.2 创建 Service 接口和实现类
import com.baomidou.mybatisplus.extension.service.IService;
import com.mybatisplus.entity.User;
/**
* UserService 继承 IService 模板提供的基础功能
*/
public interface UserService extends IService<User> {
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mybatisplus.entity.User;
import com.mybatisplus.mapper.UserMapper;
import com.mybatisplus.service.UserService;
import org.springframework.stereotype.Service;
/**
* ServiceImpl 实现了 IService,提供了 IService 中基础功能的实现
* 若 ServiceImpl 无法满足业务需求,则可以使用自定的 UserService 定义方法,并在实现类中实现
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
7.3 测试查询记录数
@Autowired
private UserService userService;
@Test
public void testGetCount(){
long count = userService.count();
System.out.println("总记录数:" + count);
}
7.4 测试批量插入
@Test
public void testSaveBatch(){
// SQL长度有限制,海量数据插入单条 SQL 无法实行,
// 因此MP将批量插入放在了通用 Service 中实现,而不是通用Mapper
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 5; i++) {
User user = new User();
user.setName("ybc" + i);
user.setAge(20 + i);
users.add(user);
}
// SQL:INSERT INTO t_user ( username, age ) VALUES ( ?, ? )
userService.saveBatch(users);
}