MyBatis-Plus —— 核心功能

1.MyBatis-Plus-CRUD增强

1.1基于baseMapper的CRUD

// mybatis-plus: 1.mapper接口 extends BaseMapper<T>
// mapper接口

public interface UserMapper extends BaseMapper<User> {}
// mybatis-plus: 2.crud 方法 crud的sql

@SpringBootTest
public class MybatisPlusTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test_insert(){
        User user = new User();
        user.setAge(188);
        user.setName("gousheng");
        user.setEmail("xxx.@QQ");
        // baseMapper 提供的数据库插入方法
        int row = userMapper.insert(user);
    }

    @Test
    public void test_delete(){

        // 根据id删除
        int rows = userMapper.deleteById(1736935624016977922L);
        System.out.println("rows = " + rows);

        // 根据age删除 map形式
        HashMap param = new HashMap();
        param.put("age",20);  // 转为 age=20 and name=xx
        userMapper.deleteByMap(param);
        System.out.println("param = " + param);

        // wrapper 条件封装对象,无限的封装条件
        // userMapper.delete(wrapper)
    }

    @Test
    public void test_update(){

        /* todo:update 当属性值为null的时候,不修改值
                建议实体类型使用包装类型,可以置空
                updateById 实体类id必须有值
         */

        // 将user id=1 的age改为30
        User user = new User();
        user.setId(1L);
        user.setAge(30);
        int i = userMapper.updateById(user);
        // update user set age = 30 where id = 1
        System.out.println("i = " + i);

        // 将所有人的年龄改为18
        User user1 = new User();
        user1.setAge(18);
        int rows = userMapper.update(user, null); //null:没条件
        System.out.println("rows = " + rows);
    }


    @Test
    public void test_select(){

        User user = userMapper.selectById(1);
        System.out.println("user = " + user);

        // ids集合查询
        List<Long> ids = new ArrayList<>();
        ids.add(1L);
        ids.add(2L);
        List<User> users = userMapper.selectBatchIds(ids);
        System.out.println("users = " + users);
    }
}

1.2 基于IService的CRUD

接口继承IService接口

public interface UserService extends IService<User> {
}

类继承ServiceImpl实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{

}

2.分页查询

2.1 将mybatis-plus的分页插件加入ioc容器

//启动类

@SpringBootApplication
@MapperScan("com.atplus.mapper")
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }

    //todo:mybatis-plus插件加入到ioc容器
    public MybatisPlusInterceptor plusInterceptor(){
        //todo:mybatis-plus的插件集合[将所需插件加入到这个集合中即可,如分页插件、乐观锁插件..]
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

        //分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new 			      				PaginationInnerInterceptor(DbType.MYSQL));

        return  mybatisPlusInterceptor;
    }

}

2.2 直接使用分页功能

@Test
public void testPage(){

    // IPage -> Page(页码,页容量)
    Page<User> page = new Page<>(1,3);
    userMapper.selectPage(page,null);

    // 结果 page最后被封装为结果
    long current = page.getCurrent(); //页码
    long size = page.getSize(); //页容量
    List<User> records = page.getRecords(); //当前页的数据
    long total = page.getTotal(); //总条数

}

2.3 自定义mapper 方法使用分页

1. 自定义方法

//自定义分页查询方法 
//根据年龄查询 且 age>xx ,返回结果为IPage

IPage<User> queryByAge(IPage<User> page,@Param("age") Integer age);

2. 方法对应实现

<!--  查询的是集合泛型,page的泛型<User>  -->
<select id="queryByAge" resultType="user">
    select * from user
    where age > #{age}
</select>

3. 测试

@Test
public void testMyPage(){
    Page<User> page = new Page<>(1,3);
    userMapper.queryByAge(page,1);

    long current = page.getCurrent(); //页码
    System.out.println("current = " + current);

    long size = page.getSize(); //页容量
    System.out.println("size = " + size);

3.条件构造器的使用

3.1 作用

使用MyBatis-Plus的条件构造器,你可以构建灵活、高效的查询条件,而不需要手动编写复杂的 SQL 语句。它提供了许多方法来支持各种条件操作符,并且可以通过链式调用来组合多个条件。这样可以简化查询的编写过程,并提高开发效率。

   @Test
    public void test01(){
        //查询用户名包含a like,年龄在20到30之间,并且邮箱不为null的用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name","a");
        queryWrapper.between("age",20,30);
        queryWrapper.isNotNull("email");

        // 链式调用(对上面单个查询语句的简化)
        queryWrapper.like("name","a").between("age",20,30)
                .isNotNull("email");

        //以上:select * from user where name like '%a%' and age between 20 and 30 and email is not null
        List<User> list = userMapper.selectList(queryWrapper);
    }

3.2 结构图

在这里插入图片描述

Wrapper:条件构造顶层抽象类

QueryWrapper:查询/删除条件封装 UpdateWrapper:修改条件封装

AbstractLambdaWrapper:Lambda语法

​ LambdaQueryWrapper 查询 LambdaUpdateWrapper 更新

QueryWrapper、LambdaQueryWrapper

@Test
public void test01(){
    //查询用户名包含a like,年龄在20到30之间,并且邮箱不为null的用户信息
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    // 链式调用
    queryWrapper.like("name","a").between("age",20,30)
        .isNotNull("email");

    //LanbdaQueryWrapper
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

    lambdaQueryWrapper.like(User::getName,"a")
        .between(User::getAge,20,30)
        .isNotNull(User::getEmail);

    //以上:select * from user where name like '%a%' 
    // and age between 20 and 30 and email is not null
    // List<User> list = userMapper.selectList(queryWrapper);
    List<User> list = userMapper.selectList(lambdaQueryWrapper);
}

updateWrapper、LambdaUpdateWrapper

 @Test
    public void test02(){
        //将年龄大于20并且用户名中包含有a或邮箱为null的用户信息修改
        //UPDATE t_user SET age=?, email=? WHERE username LIKE ? AND age > ? OR email IS NULL)
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();

        updateWrapper.gt("age",20)
                .like("name","a")
                .or().isNull("email")
                .set("email",null)
                .set("age",99);   // .默认为and | or() 为or


        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.gt(User::getAge,20)
                .like(User::getName,"a")
                .or().isNull(User::getEmail)
                .set(User::getEmail,null)
                .set(User::getAge,99);

        //int update = userMapper.update(null, updateWrapper);
        int update = userMapper.update(null, lambdaUpdateWrapper);
    }

4.核心注解

MyBatis-Plus提供了一种基于注解的方式来定义和映射数据库操作,其中的注解起到了重要作用。

4.1 @TableName

表名注解,表示实体类对应的表

实体类 @TableName(“表名”)

注:当实体类和表名相同时,可省略该注解

other:当数据库表命名规范,有统一前缀时,可将前缀提取到配置文件

mybatis-plus: # mybatis-plus的配置
  global-config:
    db-config:
      # 配置MyBatis-Plus操作表的默认前缀
      table-prefix: t_
      # 配置MyBatis-Plus的主键策略
      id-type: auto

4.2 @TableId

实体类主键字段

todo:主键不赋值
        雪花算法 默认:
            1.数据库主键 bigint(long/ varchar(64)
            2.生成不重复的数字long类型
            优点:对一张表大量数据拆分时,主键不存在重复问题
                雪花算法是一种简单但有效的生成唯一ID的算法,广泛应用于分布式系统中,如微服务架构、分布式数据库、分布式锁等场景,以满足全局唯一标识的需求。
        自增长:auto
            1.数据库 表主键 数字类型 auto_increment
            配置:
                1.实体类:@TableId(value = "id",type = IdType.AUTO)
                2.配置类:
                	mybatis-plus:
					  global-config:
    					db-config:
						  # 配置MyBatis-Plus的主键策略
      					  id-type: auto

4.3 @TableField

非主键字段

@TableField(value = "name",exist = true) 
//exist=false时,即name不为数据库表的字段,不会检索
private String name;
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值