1.MyBatis-Plus简介:
MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。MyBatis-Plus提供了通用的mapper和service,可以在不编写任何SQL语句的情况下,快速的实现对单表的CRUD批量、逻辑删除、分页等操作。
2.BaseMapper提供的CRUD功能
2.1 添加功能:
java
@Test
public void insert(){
User user = new User();
user.setName("users");
user.setAge(43);
user.setEmail("users@xja.com");
int result = this.userMapper.insert(user);
}
2.2 删除功能:
2.2.1 deleteById:
java
@Test
public void deleteById(){
int result = this.userMapper.deleteById(1696801209841856514L);
}
2.2.2 deleteByMap:
java
@Test
public void deleteByMap(){
Map<String,Object> map = new HashMap<>();
map.put("name","admin");
map.put("age",40);
int result = this.userMapper.deleteByMap(map);
}
2.2.3 deleteBatchIds(批量删除):
java
@Test
public void deleteBatchIds(){
List<Long> ids = Arrays.asList(1L, 2L, 3L);
int result = this.userMapper.deleteBatchIds(ids);
}
2.2.4 delete(根据条件删除):
java
@Test
public void delete() {
User user = new User();
user.setName("zhangsan");
user.setAge(40);
QueryWrapper<User> wrapper = new QueryWrapper<>(user);
this.userMapper.delete(wrapper);
}
2.3 修改功能:
2.3.1 updateById:
java
@Test
public void updateById(){
User user = new User();
user.setId(1L);
user.setName("Tom");
user.setAge(40);
int result = this.userMapper.updateById(user);
}
2.3.2 update(根据条件修改):
java
@Test
public void update() {
User user = new User();
user.setAge(80); // 需要更新的字段
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "Jack"); // 设置更新条件
// 执行更新操作
int result = this.userMapper.update(user, wrapper);
}
2.4 查询功能:
2.4.1 selectById:
java
@Test
public void selectById() {
User user = this.userMapper.selectById(1L);
System.out.println(user);
}
2.4.2 selectBatchIds:
java
@Test
public void selectBatchIds() {
List<Long> ids = Arrays.asList(1L, 2L, 3L, 4L, 5L);
List<User> users = this.userMapper.selectBatchIds(ids);
users.forEach(System.out::println);
}
2.4.3 selectOne:
java
@Test
public void selectOne() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "Tom");
// 只能查询一条数据,如果超过一条则报错
User user = this.userMapper.selectOne(wrapper);
System.out.println(user);
}
2.4.4 selectAll:
java
@Test
public void selectAll(){
//通过条件构造器查询一个list集合,若没有条件,则可以设置null 为参数
List<User> userList = this.userMapper.selectList(null);
userList.forEach(System.out::println);
}
2.4.5 selectCount(根据wrapper查询中记录数):
java
@Test
public void selectCount() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.gt("age", 23); //查询年龄大于23岁的成员信息
Integer count = this.userMapper.selectCount(wrapper);
System.out.printf("总记录数:%d", count);
}
2.4.6 selectList:
java
@Test
public void selectList() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.lt("age", 50); // 年龄小于50岁
List<User> users = this.userMapper.selectList(wrapper);
users.forEach(System.out::println);
}