mybatis-plus实战

前提:mybatis-plus环境搭建

1.建立测试表,建立一个springboot工程
建表:

CREATE TABLE user
(
    id BIGINT(20)NOT NULL COMMENT '主键ID',
    NAME VARCHAR(30)NULL DEFAULT NULL COMMENT '姓名',
    age INT(11)NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50)NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email)VALUES
(1, 'zheng', 18, 'test1@baomidou.com'),
(2, 'zhang', 20, 'test2@baomidou.com')

创建springboot工程:
在这里插入图片描述
2.导入依赖

       <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        <!--lombok用来简化实体类-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

3.配置文件配置

server.port=8081
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=

# 控制台上打印日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4.service,serviceimpl,mapper层

//启动类
@SpringBootApplication
@MapperScan("com.zgw.mapper")
public class mybatisplusApplication {
    public static void main(String[] args) {
        SpringApplication.run(mybatisplusApplication.class,args);
    }
}
//service
public interface UserService extends IService<User> {
}
//serviceimpl
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
//mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}

一.自动填充创建时间和更新时间

1.在表中中添加create_time,update_time,类型为datetime

2.实体类上配置

    /**
     * 下面的为了自动生成当前这两个数据,不需要我们写代码
     */
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

3.配置自动添加字段

@Component
public class MyMetaObjectHandler implements MetaObjectHandler{

    /**
     * 插入和修改时执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    /**
     * 修改时执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

二.简单crud(service层)

    /**
     * 二.插入操作
     */
    @Test
    void insertUser(){
        User user = new User();
        user.setAge(30);
        user.setEmail("435875@qq.com");
        user.setName("一个人才");
        userService.save(user);
    }

    /**
     * 三.更新操作
     * 根据用户id来进行更新操作
     * 我们只需要插入传入User对象,同时这个对象是带id的即可
     */
    @Test
    void updateUser(){
        User user = new User();
        user.setId("1");
        user.setAge(30);
        user.setEmail("23478326482@qq.com");
        user.setName("zhangzhongxiu");
        userService.updateById(user);
    }

    /**
     * 四.删除操作
     * 根据用户id进行单一删除操作
     * 根据用户id集合进行同时删除多个用户
     */
     @Test
    void deleteUser(){
         userService.removeById("1379968323089956866");
         userService.removeByIds(Arrays.asList("1","2","3","4"));
     }

    /**
     * 五.简单查询
     */
     @Test
     void selectUser(){
         userService.list();//查询所有用户
         userService.getById("1");//根据id查询
     }

三.动态条件查询(QueryWrapper)

    /**
     * 六.动态条件查询(QueryWrapper)
     */
    @Test
    void selectQueryWrapper(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = new User();
        //ge、gt、le、lt、isNull、isNotNull -> 大于等于 大于 小于等于 小于 为空 不为空 注意:需要链式使用
        wrapper.ge(user.getId()!=null,"id",user.getId())
                .le(user.getAge()!=null,"age",user.getAge())
                .isNull("email")
                .isNotNull("name");

        //eq、ne -> 等于 不等于
        wrapper.eq(user.getId()!=null,"id",user.getId())
                .ne(user.getName()!=null,"name",user.getName());

        //between、notBetween -> 在区间内 不再区间内
        wrapper.between("id","1","10")
                .notBetween("age",1,10);

        //like、notLike、likeLeft、likeRight -> 模糊查询
        wrapper.like(user.getName()!=null,"name",user.getName())
                .notLike(user.getEmail()!=null,"email",user.getEmail());

        //orderBy、orderByDesc、orderByAsc -> 默认升序 降序 升序
        wrapper.orderBy(user.getAge()!=null,true, "age");
        wrapper.orderByDesc(user.getAge()!=null,"age");
        wrapper.orderByAsc(user.getAge()!=null,"age");
    }

四.链式动态条件查询(LambdaQueryWrapper)

    /**
     * 七.链式动态条件查询(LambdaQueryWrapper)
     * 注意:链式编程的好处是改变了数据库里面的字段名称不会影响到代码,其他用法基本一致
     */
    @Test
    void selectLambdaQueryWrapper(){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        User user = new User();
        user.setId("2");
        wrapper.eq(user.getId()!=null,User::getId,user.getId());
        User one = userService.getOne(wrapper);
        System.out.println(one);
    }

五.更新条件构造器(UpdateWrapper)

    /**
     * 八.更新条件构造器(UpdateWrapper)
     */
     @Test
     void updateQueryWrapper(){
         UpdateWrapper<User> wrapper = new UpdateWrapper<>();
         User user = new User();
         user.setName("updateWrapper");
         wrapper.eq("id","2");
         userService.update(user,wrapper);
     }

六.分页查询

1.添加分页插件配置

@Configuration
public class MybatisPlusConfig {
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

2.具体操作

    /**
     * 八.分页查询
     *   1.添加分页插件配置
     *   2.进行以下的操作进行具体分页操作
     */
    @Test
    void pageSelectUser(){
        Page<User> page = new Page<>(1,3);
        Page<User> userPage = userService.page(page, null);
        //userMapper.selectPage(page,null);
        //返回对象得到分页所有数据
        long pages = userPage.getPages(); //总页数
        long current = userPage.getCurrent(); //当前页
        List<User> records = userPage.getRecords(); //查询数据集合
        long total = userPage.getTotal(); //总记录数
        boolean hasNext = userPage.hasNext();  //下一页
        boolean hasPrevious = userPage.hasPrevious(); //上一页
    }

七.逻辑删除:只会改变字段状态,不是真正意义上的删除

1.在数据库中新增一个字段:deleted,类型为int

2.在相应的实体类添加@TableLogic

    @TableLogic
    private Integer deleted;

3.application.properties(yml)文件中配置相应的配置,1:逻辑删除,0:不删除

# 1代表逻辑删除,0代表不删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

八.关于and()和or()的一些理解

当我们不用时,默认直接拼接,有时候会出现问题,用and()可以把条件放在一个()里,有时候需要这么做

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值