Service
对于一些简单的业务,只需要使用MyBatis-plus提供的通用Service即可,再有其他复杂业务,再在该service上进行扩展,使用步骤如下
- 创建mapper接口继承
BaseMapper<实体>
@Mapper
public interface StudentMapper extends BaseMapper<Student> {}
- 创建service接口继承
IService<实体>
public interface StudentService extends IService<Student> {}
- 创建service类实现service接口,继承
ServiceImpl<实体Mapper, 实体>
接口
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {}
- 编写程序进行使用
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserService userService;
@Test
public void testSelect() {
List<Student> studentList = userService.list();
Assertions.assertEquals(5, studentList.size());
}
}
查询
简单查询
方法名 |
描述 |
T getById(Serializable id) |
根据单个ID查询单个实体 |
Collection<T> listByIds(Collection<? extends Serializable> idList) |
根据多个ID查询多个实体 |
T getOne(Wrapper<T> queryWrapper, boolean throwEx) |
根据Wrapper条件查询出一个实体,第二个参数代表当查询出多个时是否报错,有一个没有第二个参数的重载,默认不报错,返回第一条 |
Collection<T> listByMap(Map<String, Object> columnMap) |
根据Map等值查询多个实体,Map的key是列名,value是条件 |
Map<String, Object> getMap(Wrapper<T> queryWrapper) |
根据Wrapper条件查询出单个实体,并且封装成map |
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper) |
根据Wrapper条件查询出多个实体,并且封装成map,有一个没有参数的重载,无条件查询出所有 |
List<T> list(Wrapper<T> queryWrapper) |
根据Wrapper条件查询出多个实体,有一个没有参数的重载,无条件查询出所有 |
int count(Wrapper<T> queryWrapper); |
根据Wrapper条件查询出符合条件的记录数,有一个没有参数的重载,无条件查询出所有 |
分页查询
方法名 |
描述 |
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper) |
根据page配置对象和Wrapper条件,进行分页查询,并封装成map,有一个没有第二个参数的重载,无条件分页查询 |
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper) |
根据page配置对象和Wrapper条件,进行分页查询,有一个没有第二个参数的重载,无条件分页查询 |
插入
方法名 |
描述 |
boolean save(T entity) |
根据实体插入一条记录,自动回写ID值 |
boolean saveBatch(Collection<T> entityList) |
根据实体集合批量插入记录,自动回写ID值 |
boolean saveOrUpdate(T entity) |
如果当前实体没有设置ID就是insert语句,否则会先根据ID进行查询,如果存在进行update,如果不存在进行insert语句 |
boolean saveOrUpdateBatch(Collection<T> entityList) |
批量存储或更新操作 |
修改
方法名 |
描述 |
boolean update(T updateEntity, Wrapper<T> whereWrapper) |
根据UpdateWrapper查询,根据实体更新,即实体出现在set子句中,UpdateWrapper出现在where子句中,其实[UpdateWrapper](# UpdateWrapper常用方法)中也有set方法可设置set子句的内容,所以可将实体设置为null |
boolean update(Wrapper<T> updateWrapper) |
根据UpdateWrapper查询和更新 |
boolean updateById(T entity) |
根据实体ID去更新其他属性,如果其他属性为null则不会出现在set中 |
boolean updateBatchById(Collection<T> entityList) |
根据实体ID去批量更新实体,如果其他属性为null则不会出现在set中 |
删除
方法名 |
描述 |
boolean removeById(Serializable id) |
根据单个ID批量删除单个实体 |
boolean remove(Wrapper<T> queryWrapper) |
根据Wrapper条件删除实体 |
boolean removeByMap(Map<String, Object> columnMap) |
根据Map等值删除多个实体,Map的key是列名,value是条件 |
boolean removeByIds(Collection<? extends Serializable> idList) |
根据多个ID批量删除多个实体 |
Comments NOTHING