Mybatis-Plus详细使用

Posted SmallCuteMonkey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis-Plus详细使用相关的知识,希望对你有一定的参考价值。


1.SpringBoot导入依赖

spring-boot-starter-parent org.springframework.boot 2.0.1.RELEASE
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>


<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
</dependency>

<!--Mybatis-Plus 注意版本-->
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.4.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.46</version>
</dependency>


<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

2.配置application.yml文件

2.1 注意url的配置需要加上后面的东西 数据库后面

?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai

2.2Mybatis-plus有自己的日志处理配置

#控制台打印sql
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl·
server:
  port: 1000

spring:
  application:
    name: SM
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/twoclass?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: roothouzhicong
#控制台打印sql
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#逻辑删除配置
  global-config:
    db-config:
      logic-delete-field: flag
      logic-delete-value: 1 #逻辑已删除默认为1
      logic-not-delete-value: 0 #逻辑没有删除字段0

3.dao层的创建使用 注意启动文件Application.java加上@MapperScan(“com.hou.dao”)

package com.hou.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hou.pojo.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserDao extends BaseMapper<User> {
}

4.pojo实体类的创建 (注意一下createTime和updateTime的填充机制)

package com.hou.pojo;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor

@TableName
public class User {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private String email;
    private Integer age;

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;




    @TableLogic
    private Integer deleted;

    @Version
    private Integer version;


    public User( String username, String password, String email, Integer age) {

        this.username = username;
        this.password = password;
        this.email = email;
        this.age = age;
    }

    public User(Integer id, String username, String password, String email, Integer age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
        this.age = age;
    }
}

5.使用controller层进行相关的测试工作

package com.hou.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hou.dao.UserDao;
import com.hou.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserDao userDao;

    @RequestMapping("/list")
    public List<User> queryAllUser(){

        List<User> users = userDao.selectList(null);
        System.out.println(users);
        return users;

    }
/*
    @RequestMapping("/queryByPage")
    public List<User> queryByPe(){

        Page<User> userPage=new Page<>();

    }*/

//    批量查询
@RequestMapping("/queryBatch")
public List<User> queryManyUser(){
    List<User> users = userDao.selectBatchIds(Arrays.asList(3, 10, 11));


    return users;

}
//条件查询根据多个条件进行相关的查询
@RequestMapping("/queryByMap")
public List<User> queryByMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("age", 22);
    map.put("password", "sdfds");
    List<User> users = userDao.selectByMap(map);
    return users;
    }

/*
    条件构造器Wrapper
1.查询name不为null的用户,并且邮箱不为null的永不,年龄大于等于22的用户*/
    @RequestMapping("/queryByWarpper")
    public List<User> queryByWarpper() {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.isNotNull("username");
        queryWrapper.isNotNull("email");
        queryWrapper.ge("age",22);

        List<User> users = userDao.selectList(queryWrapper);
        return users;
    }

    /*
    * 条件查询的构造器
    * 2.查询年龄在20-30之间的用户信息,和用户个数
    *
    * */
    @RequestMapping("/queryByWarpper1")
    public List<User> queryByWarpper1() {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();

        queryWrapper.between("age",20,30);

        List<User> users = userDao.selectList(queryWrapper);
        Integer count = userDao.selectCount(queryWrapper);
        System.out.println(count);

        return users;
    }

    /*
    * 模糊查询
    * */

    @RequestMapping("/queryByWarpper2")
    public void queryByWarpper2() {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();

        queryWrapper.notLike("name","z"); //相当于 NOT LIKE '%Z%'
        queryWrapper.likeLeft("email","@qq.com"); //相当于 like '%@qq.com'
        List<Map<String, Object>> maps = userDao.selectMaps(queryWrapper);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }


    }

    /*
    * 测试子查询
    *
    * */

    @RequestMapping("/queryByWarpper3")
    public void queryByWarpper3() {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();

       //子查询
        queryWrapper.inSql("id","select id from user where id<5");

        List<Object> objects = userDao.selectObjs(queryWrapper);
        for (Object object : objects) {
            System.out.println(object);
        }
//        降序进行查询
//        queryWrapper.orderByAsc("age");


    }




















    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public int addUser(){

       User user=new User(9,"houzhicong","66666","233@qq.com",18);
        int i = userDao.insert(user);
        return i;

    }

    @RequestMapping(value = "/delBatch",method = RequestMethod.DELETE)
    public int deletUser(){
//批量删除功能实现
        int i = userDao.deleteBatchIds(Arrays.asList(2, 6, 9));
        return i;

    }

    @RequestMapping(value = "/delbyid",method = RequestMethod.DELETE)
    public int deletUserByid(){
//批量删除功能实现
        int i = userDao.deleteById(20);
        return i;

    }

    @RequestMapping(value = "/up",method = RequestMethod.PUT)
    public int upUserByid(){

        User user=new User(3,"houzhicong","666666","233@qq.com",18);
        int i = userDao.updateById(user);
        return i;

    }










}

6.时间的填充机制需要创建一个配置文件类,创建一个config包,下面加上配置类:

package com.hou.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component //不要忘记吧处理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {

    //插入时候的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");  //日志
        //设置字段的值(String fieldName字段名,Object fieldVal要传递的值,MetaObject metaObject)
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }

    //更新时间的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }
}

7.分页插件的配置文件

package com.hou.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@Configuration
@MapperScan("com.hou.dao")
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

}

8.Mybatis-Plus也可以进行mapper.xml文件的使用这个没有改变mybatis的使用

9.也可以使用逆向工程生成相关的controller,dao,pojo,service层。

10.注意一下springBoot2.0已经有自己的默认的连接池了 HikariCp(号称性能最好的连接池)

以上是关于Mybatis-Plus详细使用的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis-Plus中的代码生成器AutoGenerator超详细解析!完整配置!

Mybatis-Plus中的代码生成器AutoGenerator超详细解析!完整配置!

mybatis-plus详细使用教程

Mybatis-Plus详细使用

SpringBoot整合MyBatis-Plus3.1详细教程

Mybatis-Plus学习小项目及详细教程