Mybatis-Plus | Use Mybatis-Plus for paging query

MyBatis-Plus (MP for short) is an enhancement tool for MyBatis. On the basis of MyBatis, it only enhances and does not change. It is born to simplify development and improve efficiency.
Features of MyBatis-Plus:
No intrusion : only enhance and do not change, the introduction of it will not affect the existing project, it is as smooth as silk, and the loss is small: the basic CURD will be automatically injected at startup, the performance is basically no loss, and it is directly object-oriented Operate
powerful CRUD operations : built-in general Mapper, general service, only a small amount of configuration can realize most of the CRUD operations of a single table, more powerful condition constructor, to meet all kinds of usage needs,
support Lambda form invocation : through Lambda expression, Conveniently write all kinds of query conditions, no need to worry about writing wrong fields.
Support automatic primary key generation : support up to 4 primary key strategies (including distributed unique ID generator-Sequence), freely configurable, and perfect solution to primary key issues.
Support ActiveRecord mode : Support ActiveRecord form call, entity classes only need to inherit Model class to perform powerful CRUD operations.
Support custom global general operations : Support global general method injection (Write once, use anywhere)
Built-in code generator : use code or Maven plug-in Quickly generate Mapper, Model, Service, Controller layer code, support template engine, and more custom configurations, etc. You can use the
built-in paging plug-in : Based on MyBatis physical paging, developers don’t need to care about specific operations. After configuring the plug-in, write the paging Equivalent to ordinary List query
Paging plug-in supports a variety of databases : supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other database
built-in performance analysis plug-ins : Sql statements and their execution time can be output, it is recommended to enable this function during development and testing , Can quickly uncover slow queries.
Built-in global interception plug-in : Provides full table delete and update operation intelligent analysis and blocking, and can also customize interception rules to prevent misoperation

One, Maven dependency

	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>

2. The core configuration file (application.properties)

# 端口
server.port=8081
# 上下文
server.servlet.context-path=/swagger
# 驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# url
spring.datasource.url=jdbc:mysql://localhost:3306/excel?useUnicode=true&characterEncoding=utf-8
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=123456
# 映射文件文件路径
mybatis-plus.mapper-locations=classpath:/com/jonsson/dao/*Dao.xml
# 类型别名
mybatis-plus.type-aliases-package=com.jonsson.entity
# 打印sql
logging.level.root.com.jonsson.dao=debug

Three, MVC extension-register paging interceptor object (MybatisPlusConfig)

@Configuration
@Slf4j
public class MybatisPlusConfig {
    
    
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    
    
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        log.debug("配置mybatis-plus分页插件");
        // 方言
        paginationInterceptor.setDialectType("mysql");
        return paginationInterceptor;
    }
}

Four, entity entity class

@Data
public class Car {
    
    
    private Integer id;
    private String name;
    private Integer price;
    private String colour;
    private String brand;
}

Five, dao interface

@Repository
@Mapper
public interface CarDao extends BaseMapper<Car> {
    
    

}

Six, service interface and implementation class

public interface CarService {
    
    
    public IPage<Car> findAll();
}
@Service
public class CarServiceImpl implements CarService {
    
    
    @Autowired
    private CarDao carDao;

    @Override
    public IPage<Car> findAll() {
    
    
    	// 第一个参数是当前页,第二个参数是页大小
        Page<Car> carPage = new Page<>(1, 2);
        return carDao.selectPage(carPage, null);
    }
}

Seven, controller

@RestController
@Slf4j
public class CarController {
    
    
    @Autowired
    private CarService carService;

    @RequestMapping("/carPage")
    public ResultVO<Object> carPage() {
    
    
        IPage<Car> carIPage = carService.findAll();
        log.debug(carIPage.toString());
        if (carIPage.getRecords().size() > 0) {
    
    
            return ResultVOUtils.success(carIPage.getRecords());
        } else {
    
    
            return ResultVOUtils.error("错误");
        }
    }
}

(、 Vo (ResultVO)

@Data
public class ResultVO<T> {
    
    
    private Integer code;
    private String msg;
    private T data;
}

Nine, util (ResultVOUtils)

public class ResultVOUtils {
    
    
    public static ResultVO<Object> success(Object object) {
    
    
        ResultVO<Object> objectResultVO = new ResultVO<>();
        objectResultVO.setCode(0);
        objectResultVO.setMsg("成功");
        objectResultVO.setData(object);
        return objectResultVO;
    }

    public static ResultVO<Object> success() {
    
    
        ResultVO<Object> objectResultVO = new ResultVO<>();
        objectResultVO.setCode(0);
        objectResultVO.setMsg("成功");
        objectResultVO.setData(null);
        return objectResultVO;
    }

    public static ResultVO<Object> error(String msg) {
    
    
        ResultVO<Object> objectResultVO = new ResultVO<>();
        objectResultVO.setCode(1);
        objectResultVO.setMsg(msg);
        return objectResultVO;
    }
}

Nine, database script

DROP TABLE IF EXISTS `car`;
CREATE TABLE `car` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(255) DEFAULT NULL COMMENT '名称',
  `price` int(11) DEFAULT NULL COMMENT '价格',
  `colour` varchar(255) DEFAULT NULL COMMENT '颜色',
  `brand` varchar(255) DEFAULT NULL COMMENT '品牌',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='汽车';
LOCK TABLES `car` WRITE;
INSERT INTO `car` VALUES (1,'丰田',100,'黑色','丰田'),(2,'大众',150,'白色','大众'),(3,'东风',120,'蓝色','东风'),(4,'凯迪拉克',150,'黑色','凯迪拉克'),(5,'奥迪',200,'红色','奥迪'),(6,'凯迪拉克',150,'黑色','凯迪拉克'),(7,'奥迪',200,'红色','奥迪'),(8,'宝马',300,'灰色','宝马');
UNLOCK TABLES;

Request result

Insert picture description here

Guess you like

Origin blog.csdn.net/y1534414425/article/details/105638684