依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.2</version>
</dependency>
编写mapper
/*
TODO: mp需要dao层接口继承BaseMapper接口
1. BaseMapper底层封装了很多方法
1). 返回值类型不知道 -> 泛型指定JavaBean类型
比如 BaseMapper<User>
2. 自动进行sql配置
1). 表名不知道
默认是javaBean的类名
如果类名跟表名不一致,需要在类名上加注解 @TableName("tb_user")
2). 主键字段名不知道
默认找名为id的属性
如果不一致, 需要在属性上加 @TableId("id")
3). 非主键字段名不知道
默认跟属性名一致, 注意自动小驼峰映射(守护星userName 映射 字段 user_name)
如果不一致,需要在属性上加 @TableField("password")
*/
//@Mapper
public interface UserMapper extends BaseMapper<User> {
// @Select("select * from tb_user where id = #{id}")
// User selectById(Long id);
// @Update("update tb_user set pwd = #{password},user_name= #{userName},name=#{name} where id = #{id}")
// int updateById(User user);
}
插入
@Test
public void insert(){
/*
TODO: mp的insert方法的主键生成策略
1. 主键自增
IdType.AUTO
主键字段必须number,并且设置了自增
(单体架构)
2. 雪花算法 (默认)
IdType.ASSIGN_ID
1). 可自增的10进制随机数
2). 要求主键类型是number或字符串
(分布式)
3. uuid
IdType.ASSIGN_UUID
1). 16进制随机数
2). 要求主键字段类型为字符串(char,varchar)
*/
// User user = new User(null, "张三", "123", "瘪三", 18, "zs@itcast.cn");
//建造者模式
User user = User.builder()
.userName("张三")
.password("123")
.age(18)
.email("zs@itcast.cn").build();
int count = mapper.insert(user);
System.out.println("被影响的行数:" + count); // 1
}
}
删除
int count = userMapper.deleteById(8L); //根据id删除
List ids = new ArrayList(); //根据id集合批量删除
ids.add(6);
ids.add(7);
userMapper.deleteBatchIds(ids);
Map<String, Object> map = new HashMap<>(); //根据map构造条件,删除
//delete from tb_user where user_name = ? and age = ?
map.put("user_name","itcast");
map.put("age","18");
userMapper.deleteByMap(map);
更新
@Test
public void testUpdateById() {
User user = new User();
user.setId(2L);
user.setPassword("1111111");
int count = userMapper.updateById(user);
}
配置分页拦截器
package com.itheima.sh.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Description:
* @Version: V1.0
1. 此配置类的目的创建一个分页拦截器
2. 此拦截器会被加入到IOC容器中
3. MP的底层会获取此拦截器并拦截所有查询方法
效果: 只要设置此拦截器,本工程的所有查询只要调用对应的API就都有分页效果
*/
@Configuration
public class MybatisPlusConfig {
//此方法的返回值被添加IOC容器中
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//创建分页拦截器
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); // 方言
interceptor.addInnerInterceptor(paginationInterceptor);
return interceptor;
}
}
/**
* 分页查询:
* 1. 当前页码:currentPage
* 2. 每页显示条数:size
*
* 注意:使用mp的分页要设置一个拦截器!!!
*/
@Test
public void testSelectPage() {
int current = 1;//当前页码
int size = 2;//每页显示条数
IPage<User> page = new Page(current,size);
userMapper.selectPage(page,null);
List<User> records = page.getRecords();//当前页的数据
long pages = page.getPages();//总页数 2
long total = page.getTotal();//总记录数 4
System.out.println(records);
System.out.println(pages);
System.out.println(total);
}
QueryWrapper实现基础查询
QueryWrapper常用API
eq( ) : 等于 = (equals)
ne( ) : 不等于 <> (not equals)
gt( ) : 大于 > (greater than)
ge( ) : 大于等于 >= (greater than or equals)
lt( ) : 小于 < (less than)
le( ) : 小于等于 <= (less than or equals)
between ( ) : BETWEEN 值1 AND 值2
notBetween ( ) : NOT BETWEEN 值1 AND 值2
in( ) : in
notIn( ) :not in
示例
@Test
public void testWrapper1() throws Exception{
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 封装查询条件
wrapper.like("user_name", "伤")
.eq("password","123456")
.in("age",19,25,29)
.orderByDesc("age","id"); // 降序 升序:asc
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
@Test
public void testWrapper2(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五");
/*
select * from tb_user where user_name = ? or age < ? and name in (?,?)
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
/**
* 模糊查询
*/
@Test
public void testWrapper3(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.likeLeft("user_name","zhang");
/*
SELECT id,user_name,password,name,age,email
from tb_user
where user_name like ?
%zhang
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
@Test
public void testWrapper4(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五")
//.orderBy(true,true,"age")
.orderByDesc("age");
/*
select * from tb_user where user_name = ? or age < ? and name in (?,?) order by age asc
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
@Test
public void testWrapper5(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五")
//.orderBy(true,true,"age")
.orderByDesc("age")
.select("id","user_name"); //限定字符串
/*
select id,user_name from tb_user where user_name = ? or age < ? and name in (?,?) order by age asc
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
QueryWrapper实现分页条件查询
@Test
public void testWrapper6(){
int current = 1;//当前页码
int size = 2;//每页显示条数
//1. 构建分页对象
Page<User> page = new Page<>(current,size);
//2. 构建条件对象
QueryWrapper<User> wrapper = new QueryWrapper();
wrapper.lt("age",23);
userMapper.selectPage(page,wrapper);
List<User> records = page.getRecords();
long total = page.getTotal();
long pages = page.getPages();
System.out.println(records);
System.out.println(total);//2
System.out.println(pages);//1
}
LambdaQueryWrapper查询
@Test
public void testWrapper4() throws Exception{
// LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
// wrapper.like("user_name", "%伤%")
// .eq("password","123456")
// .ge("age", 28)
// .between("age",29 , 39); // 包含边界值
wrapper.like(User::getUserName, "%伤%")
.eq(User::getPassword, "123456")
.ge(User::getAge, 28)
.between(User::getAge, 29, 39)
.orderByDesc(User::getAge)
.select(User::getId, User::getUserName);
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
/**
* 条件删除
* @throws Exception
*/
@Test
public void testWrapper5() throws Exception{
LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUserName, "武大郎");
int i = userMapper.delete(wrapper);
System.out.println(i);
}
/**
* 条件更新
* @throws Exception
*/
@Test
public void testWrapper6() throws Exception{
/**
* UPDATE tb_user SET t_name=? WHERE (id = ?)
*/
// 参数1: 要修改的值
User user = new User();
user.setUserName("张三丰");
// 参数2:更新时条件
LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
wrapper.eq(User::getId, 15);
int update = userMapper.update(user, wrapper);
System.out.println(update);
}
/**
* 条件更新
* @throws Exception
*/
@Test
public void testWrapper7() throws Exception{
/**
* UPDATE tb_user SET t_name=?, user_name=? WHERE (id = ?)
*/
// 参数1: 最新的值
// 参数2:更新时条件
LambdaUpdateWrapper<User> wrapper = Wrappers.<User>lambdaUpdate();
wrapper.eq(User::getId, 15)
.set(User::getUserName, "张三丰666")
.set(User::getName,"zsf666");
int update = userMapper.update(null, wrapper);
System.out.println(update);
}
MP实现Service封装
用法
//在公共接口的基础上扩展
public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {}
package com.itheima;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* @Description
* @Created by itheima
*/
@SpringBootTest
public class MpTestService {
@Autowired
private UserService userService;
/**
* @Description 测试查询操作 根据id查询
*/
@Test
public void test1(){
User user = userService.getById(3l);
System.out.println(user);
}
/**
* @Description 测试条件查询,且仅返回一个
* getOne:sql查询的结果必须为1条或者没有,否则报错 !!!!
*/
@Test
public void test2(){
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class);
wrapper.gt(User::getAge,20);
User one = userService.getOne(wrapper);
System.out.println(one);
}
/**
* @Description 根据条件批量查询
*/
@Test
public void test3(){
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class);
wrapper.gt(User::getAge,20);
List<User> list = userService.list(wrapper);
System.out.println(list);
}
/**
* @Description 根据条件批量查询并分页
*/
@Test
public void test4(){
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class);
wrapper.gt(User::getAge,20);
//构建分页对象
IPage<User> page=new Page<>(2,3);
userService.page(page,wrapper);
System.out.println(page.getRecords());
System.out.println(page.getPages());
System.out.println(page.getTotal());
}
/**
* @Description 测试服务层save保存单条操作
*/
@Test
public void test5(){
User user1 = User.builder().name("wangwu").userName("laowang4").
email("444@163.com").age(20).password("333").build();
boolean isSuccess = userService.save(user1);
System.out.println(isSuccess?"保存成功":"保存失败");
}
/**
* @Description 测试服务层批量保存
*/
@Test
public void test6(){
User user2 = User.builder().name("wangwu2").userName("laowang2").
email("444@163.com").age(20).password("333").build();
User user3 = User.builder().name("wangwu3").userName("laowang3").
email("444@163.com").age(20).password("333").build();
boolean isSuccess = userService.saveBatch(Arrays.asList(user2, user3));
System.out.println(isSuccess?"保存成功":"保存失败");
}
/**
* @Description 根据id删除操作
*/
@Test
public void test7(){
boolean isSuccess = userService.removeById(17l);
System.out.println(isSuccess?"保存成功":"保存失败");
}
/**
* @Description 根据条件批量删除
*/
@Test
public void test8(){
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class);
wrapper.gt(User::getId,12)
.gt(User::getAge,20);
boolean remove = userService.remove(wrapper);
System.out.println(remove);
}
/**
* @Description 测试根据id更新数据
*/
@Test
public void test9(){
//UPDATE tb_user SET password=?, t_name=? WHERE id=?
User user2 = User.builder().name("wangwu2").password("333").id(3l).build();
boolean success = userService.updateById(user2);
System.out.println(success);
}
/**
* @Description 测试根据条件批量更新
*/
@Test
public void test10(){
LambdaUpdateWrapper<User> wrapper = Wrappers.lambdaUpdate(User.class);
//UPDATE tb_user SET age=? WHERE (id IN (?,?,?))
wrapper.in(User::getId,Arrays.asList(1l,3l,5l)).set(User::getAge,40);
boolean update = userService.update(wrapper);
System.out.println(userService);
}
}