1.配置文件添加paginationInterceptor

@Configuration
@MapperScan("fama.cost.*.mapper")
public class SpringConnectionFactory {
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}

2.mapper

mapper与正常配置一致

3.编写测试用例

@Test
public void selectPage(){
Page<RdsInstanceType> page = new Page<>(1,2);
IPage<RdsInstanceType> page1 = rdsInstanceTypesMapper.selectPage(page, Wrappers.query());
LOG.info("total : {}",page1.getTotal());
LOG.info("pages : {}",page1.getPages());
page1.getRecords().forEach(rdsInstanceType -> {
LOG.info("instanceType : {}",JsonUtils.toJSONString(rdsInstanceType));
}); }

Dao 层

4.doa层的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>fama</artifactId>
<groupId>fama.cost</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>fama-dao</artifactId> <profiles>
<!-- 开发环境 -->
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activeEnv>dev</activeEnv>
<mysql.url>jdbc:mysql://192.168.1.1:3358/fama?rewriteBatchedStatements=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;tinyInt1isBit=false&amp;useCompression=true&amp;autoReconnect=true&amp;defaultFetchSize=100</mysql.url>
<mysql.user>test</mysql.user>
<mysql.pass>test</mysql.pass>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<activeEnv>prod</activeEnv>
<mysql.url>jdbc:mysql://192.168.1.1:3358/fama?rewriteBatchedStatements=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;tinyInt1isBit=false&amp;useCompression=true&amp;autoReconnect=true&amp;defaultFetchSize=100</mysql.url>
<mysql.user>test</mysql.user>
<mysql.pass>test</mysql.pass>
</properties>
</profile>
</profiles> <dependencies> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</exclusion>
<exclusion>
<artifactId>log4j-api</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
</dependency> <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>fama.cost</groupId>
<artifactId>fama-common</artifactId>
<version>${project.version}</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies> <build>
<plugins> <!-- <plugin>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-maven-plugin</artifactId>-->
<!-- <configuration>-->
<!-- <mainClass>sigma.resource.sync.SigmaApplication</mainClass>-->
<!-- <layout>JAR</layout>-->
<!-- </configuration>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <goals>-->
<!-- <goal>repackage</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>--> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<useDefaultDelimiters>true</useDefaultDelimiters><!-- 这是重点-->
</configuration>
<executions>
<execution>
<id>copy-fatjar</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/build</outputDirectory>
<resources>
<resource>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.${project.packaging}</include>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy resource</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/classes</outputDirectory>
<overwrite>true</overwrite>
<resources>
<resource>
<directory>${basedir}/src/main</directory>
<includes>
<include>*</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId>
<configuration>
<filesets>
<fileset>
<directory>src/main/resources/public</directory>
</fileset>
</filesets>
</configuration>
</plugin>
</plugins> <resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources> </build> </project>

5.datasource.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=@mysql.url@
spring.datasource.username=@mysql.user@
spring.datasource.password=@mysql.pass@
spring.datasource.validationQuery=SELECT 1
spring.datasource.idle.timeout=180000
spring.datasource.maximumPoolSize=10
spring.datasource.defaultAutoCommit=true
spring.datasource.maxLifetime=1800000
spring.datasource.connectionTimeout=30000

6.mapper目录是fama.cost.dao.mapper,在resource目录下,xml文件

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="fama.cost.dao.mapper.CommandMapper">
</mapper>

7.dao层里的工厂

package fama.cost.dao.datasource;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import fama.cost.common.utils.Constants;
import fama.cost.dao.utils.PropertyUtils;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import java.util.Properties; @Configuration
@MapperScan("fama.cost.*.mapper")
public class SpringConnectionFactory { private static final Logger logger = LoggerFactory.getLogger(SpringConnectionFactory.class); @Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
} @Bean(destroyMethod="")
public HikariDataSource dataSource() { HikariDataSource hikariDataSource = new HikariDataSource(); hikariDataSource.setDriverClassName(PropertyUtils.getString(Constants.SPRING_DATASOURCE_DRIVER_CLASS_NAME));
hikariDataSource.setJdbcUrl(PropertyUtils.getString(Constants.SPRING_DATASOURCE_URL));
hikariDataSource.setUsername(PropertyUtils.getString(Constants.SPRING_DATASOURCE_USERNAME));
hikariDataSource.setPassword(PropertyUtils.getString(Constants.SPRING_DATASOURCE_PASSWORD));
hikariDataSource.setConnectionTestQuery(PropertyUtils.getString(Constants.SPRING_DATASOURCE_VALIDATION_QUERY,"SELECT 1"));
hikariDataSource.setConnectionTimeout(PropertyUtils.getLong(Constants.SPRING_DATASOURCE_CONNECTION_TIMEOUT,30000));
hikariDataSource.setMaximumPoolSize(PropertyUtils.getInt(Constants.SPRING_DATASOURCE_MAX_POOL_SIZE, 10));
hikariDataSource.setIdleTimeout(PropertyUtils.getLong(Constants.SPRING_DATASOURCE_IDLE_TIMEOUT,180000));
hikariDataSource.setAutoCommit(PropertyUtils.getBoolean(Constants.SPRING_DATASOURCE_DEFAULT_AUTO_COMMIT,true));
hikariDataSource.setMaxLifetime(PropertyUtils.getLong(Constants.SPRING_DATASOURCE_MAX_LIFE_TIME,1800000));
return hikariDataSource;
} @Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
} @Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisConfiguration configuration = new MybatisConfiguration();
// configuration.setLogImpl(StdOutImpl.class);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
configuration.setCallSettersOnNulls(true);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.addInterceptor(paginationInterceptor());
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setConfiguration(configuration);
sqlSessionFactoryBean.setDataSource(dataSource()); GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
dbConfig.setIdType(IdType.AUTO);
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setDbConfig(dbConfig);
sqlSessionFactoryBean.setGlobalConfig(globalConfig);
sqlSessionFactoryBean.setTypeAliasesPackage("fama.cost.dao.entity");
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("fama/cost/dao/mapper/*Mapper.xml"));
// sqlSessionFactoryBean.setTypeEnumsPackage("fama.cost.*.fama.cost.api.enums");
sqlSessionFactoryBean.setTypeEnumsPackage("fama.cost.*.enums");
sqlSessionFactoryBean.setDatabaseIdProvider(databaseIdProvider());
return sqlSessionFactoryBean.getObject();
} @Bean
public SqlSession sqlSession() throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
} @Bean
public DatabaseIdProvider databaseIdProvider(){
DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties properties = new Properties();
properties.setProperty("MySQL", "mysql");
databaseIdProvider.setProperties(properties);
return databaseIdProvider;
}
}

8.entity 放db的实体类

package fama.cost.dao.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import fama.cost.common.enums.CommandType; import java.util.Date; @TableName(value = "fama_command")
public class Command { @TableId(value = "id", type = IdType.AUTO)
private Long id; private long orderId;
private String commandParam;
private Date applyTime;
private Date scheduleTime;
private String applyUser;
private CommandType commandType; public long getOrderId() {
return orderId;
} public void setOrderId(long orderId) {
this.orderId = orderId;
} public String getCommandParam() {
return commandParam;
} public void setCommandParam(String commandParam) {
this.commandParam = commandParam;
} public Date getApplyTime() {
return applyTime;
} public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
} public Date getScheduleTime() {
return scheduleTime;
} public void setScheduleTime(Date scheduleTime) {
this.scheduleTime = scheduleTime;
} public String getApplyUser() {
return applyUser;
} public void setApplyUser(String applyUser) {
this.applyUser = applyUser;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public CommandType getCommandType() {
return commandType;
} public void setCommandType(CommandType commandType) {
this.commandType = commandType;
}
}

9.mapper目录就是放interface接口的

package fama.cost.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import fama.cost.dao.entity.Command; public interface CommandMapper extends BaseMapper<Command> { }

10.utils里放BeanContext工具类及PropertyUtils工具类,用于加载datasoure.properties

BeanContext.java

package fama.cost.dao.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() {
return applicationContext;
} @SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
} public static <T> T getBean(Class<T> clazz) throws BeansException {
return applicationContext.getBean(clazz);
} @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContext.applicationContext = applicationContext;
}
}

PropertyUtils.java

package fama.cost.dao.utils;

import fama.cost.common.utils.Constants;
import fama.cost.common.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; public class PropertyUtils { private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class); private static final Properties properties = new Properties(); private static final PropertyUtils propertyUtils = new PropertyUtils(); private PropertyUtils(){
init();
} private void init(){
String[] propertyFiles = new String[]{Constants.DATASOURCE_PROPERTIES};
for (String fileName : propertyFiles) {
InputStream fis = null;
try {
fis = PropertyUtils.class.getResourceAsStream(fileName);
properties.load(fis); } catch (IOException e) {
logger.error(e.getMessage(), e);
if (fis != null) {
IOUtils.closeQuietly(fis);
}
System.exit(1);
} finally {
IOUtils.closeQuietly(fis);
}
}
} public static String getString(String key) {
return properties.getProperty(key);
} public static String getString(String key, String defaultVal) {
String val = properties.getProperty(key.trim());
return val == null ? defaultVal : val;
} public static int getInt(String key) {
return getInt(key, -1);
} public static int getInt(String key, int defaultValue) {
String value = getString(key);
if (value == null) {
return defaultValue;
} try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.info(e.getMessage(),e);
}
return defaultValue;
} public static Boolean getBoolean(String key) {
String value = properties.getProperty(key.trim());
if(null != value){
return Boolean.parseBoolean(value);
} return false;
} public static Boolean getBoolean(String key, boolean defaultValue) {
String value = properties.getProperty(key.trim());
if(null != value){
return Boolean.parseBoolean(value);
} return defaultValue;
} public static long getLong(String key, long defaultVal) {
String val = getString(key);
return val == null ? defaultVal : Long.parseLong(val);
}
}

mybatis-plus 分页查询+ dao层抽象的更多相关文章

  1. mybatis中分页查询

    1 如果在查询方法中有多个参数,可以使用map对象将所有数据都存储进去.比如分页查询,需要用到两个参数,可以将这两个参数包装到map中. 例子:分页查询 dao层方法 public List<S ...

  2. SSM框架之Mybatis(3)dao层开发

    Mybatis(3)dao层开发 以实现类完成CRUD操作 1.持久层dao层接口的书写 src\main\java\dao\IUserDao.java package dao; import dom ...

  3. Mybatis包分页查询java公共类

    Mybatis包分页查询java公共类   分页----对于数据量非常大的查询中.是不可缺少的. mybatis底层的分页sql语句因为须要我们自己去手动写.而实现分页显示的时候我们须要依据分页查询条 ...

  4. mybatis之分页查询

    1)StudentDao.java /** * 持久层*/ public class StudentDao { /** * 增加学生 */ public void add(Student studen ...

  5. mybatis mapper接口开发dao层

    本文将探讨使用 mapper接口,以及 pojo 包装类进行 dao 层基本开发 mybatis dao 层开发只写 mapper 接口 其中需要 开发的接口实现一些开发规范 1. UserMappe ...

  6. (二)Mybatis总结之通过Dao层与数据交互

    Mybatis概述 定义: Mybatis是一个支持普通sql查询,存储过程和高级映射的优秀持久层框架. Mybatis是(半自动的)跟数据库打交道的orm(object relationship m ...

  7. SpringBoot整合Mybatis关于分页查询的方法

    最近公司在用到SpringBoot整合Mybatis时当web端页面数据增多时需要使用分页查询以方便来展示数据.本人对分页查询进行了一些步骤的总结,希望能够帮助到有需要的博友.如有更好的方式,也希望评 ...

  8. springmvc+mybatis 实现分页查询

    为简化分页功能,设计了一个分页的JSP标签,只需要在页面使用分页标签,就可以完成所有页面的分页功能. 1. 项目结构和数据库设计 (1) 项目结构: (2) 数据库设计 2. PageModel.ja ...

  9. spring-boot 集合mybatis 的分页查询

    spring-boot 集合mybatis 的github分页查询 一.依赖包 <!-- mysql 数据库驱动. --> <dependency> <groupId&g ...

随机推荐

  1. 已知a=a

    高中时酷爱经济学. 薄薄的纸片竟然决定着整个社会的运转趋势,整个人生的起伏也是靠着纸片来衡量的. 可笑的是你怎么闹腾也逃不过康波周期等一系列命中注定的路线,即,已知a=a,那么a等于且仅等于a. 所有 ...

  2. text-align: justify 文本对齐

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 《机器学习Python实现_10_09_集成学习_bagging_stacking原理及实现》

    介绍 前面对模型的组合主要用了两种方式: (1)一种是平均/投票: (2)另外一种是加权平均/投票: 所以,我们有时就会陷入纠结,是平均的好,还是加权的好,那如果是加权,权重又该如何分配的好?如果我们 ...

  4. 影子卫士汉化语言包 res.ini

    [translate];authorinfo=Simplified Chinese Translation 简体翻译 by: Clarence [common]0=Shadow Defender 10 ...

  5. Linux-鸟菜-4-关机的正确姿势

    Linux-鸟菜-4-关机的正确姿势 这章里面鸟哥介绍了基本的登录操作以及一些基本命令还有关机的正确姿势,基本的命令我都整理到常用命令3里面了,关机的这个感觉挺重要,单独整理下. 由于Linux本身是 ...

  6. 写复杂的json方法

    <?php for($j=0; $j< 30; $j++) { $Axis[$j] = "a"; } $data['xAxis']= $Axis; for($i=0; ...

  7. redux和mobx入门使用

    redux和mobx入门使用 项目涉及技术 公共插件 create-react-app react-dom react-router react-router-dom react-hook redux ...

  8. 五、postman公共函数及newman运行与生成测试报告

    一.公共函数 postman中定义公共函数如下 1.每次断言的时候都需要重写或者复制之前的断言代码,可以通过如下方法定义断言的公共函数,以后每次断言的时候只需要调用公共函数即可进行断言 设置公共函数对 ...

  9. JavaI/O流汇总

    Java中常见流学习汇总 流的含义 流在Java中是指计算中流动的缓冲区. 从外部设备流向中央处理器的数据流成为"输入流",反之成为"输出流". 字符流和字节流 ...

  10. 4.启动虚拟机 设置CentOS7

    启动虚拟机 CentOS设置 1.点击箭头方向即可启动我们的VMware 2.设置语言 在第一步设置完成后,我们一直等待,即可来到语言设置界面 此处我们设置[中文] 3.设置安装信息 将下面带有[感叹 ...