SpringBoot MyBatis generator pagehelper 整合

Automatic code generation Project structure preview: 

Project construction:

  • Environment configuration
  • New Project

pom.xml configuration: 

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.company</groupId>
    <artifactId>springbootmybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootmybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--分页插件使用方式一-->
        <!--<dependency>-->
        <!--<groupId>com.github.pagehelper</groupId>-->
        <!--<artifactId>pagehelper</artifactId>-->
        <!--<version>4.0.0</version>-->
        <!--</dependency>-->
        <!--分页插件使用方式二-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.33</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

application.yml placement: 

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    name: Mysql
    url: jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20


## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.company.springbootmybatis.model  # 注意:对应实体类的路径

#pagehelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

 

mybatis-generator.xml configuration: 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 引入配置文件  application.yml配置文件引入失败 获取不到配置信息
                       application.properties配置文件未测试-->
    <!-- <properties resource="application.yml"/>-->

    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry location="D:\TEST_repository\mysql\mysql-connector-java\8.0.20\mysql-connector-java-8.0.20.jar"/>

    <context id="Mysql" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>


        <!--yml配置获取不到遂将数据库链接URL,用户名、密码复制此处-->
        <!--  <jdbcConnection driverClass="${spring.datasource.driver-class-name}"
                          connectionURL="${spring.datasource.url}"
                          userId="${spring.datasource.username}" password="${spring.datasource.password}">-->
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"
                        userId="root" password="root">
            <property name="useInformationSchema" value="true"/>
            <property name="remarks" value="true"/>
        </jdbcConnection>
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.company.springbootmybatis.model" targetProject="src/main/java">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用,就是去空格 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.company.springbootmybatis.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="book_test" domainObjectName="BookTest" mapperName="BookTestMapper"></table>
    </context>
</generatorConfiguration>


com.mysql.cj.jdbc.Driver driver problem:
8.0.20 used by the mysql-connector-java version, here driverClass should be configured as com.mysql. cj.jdbc .Driver instead of com.mysql.jdbc.Driver 

Caused by: java.sql.SQLException: The server time zone value' й ׼ʱ ' is unrecognized 
connectionURL initial configuration jdbc:mysql://127.0.0.1:3306/book
configuration modified to: jdbc:mysql ://localhost:3306/spring?serverTimezone=UTC 
needs to be separated by & when there are multiple params, but & should be changed to
jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding= UTF-8&serverTimezone=UTC

Code generation: 

Startup class: 

@MapperScan:

@SpringBootApplication
@MapperScan("com.company.springbootmybatis.mapper")
public class SpringbootmybatisApplication {

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

}

If the mapper injection fails, the solution:

Lower the error level of IDEA:

Controller:

Pagination:  PageHelper.startPage(pageNum, pageSize);

@RestController
@RequestMapping("/book")
public class BookTestCroll {

    @Autowired
    BookTestService bookTestService;

    @GetMapping("/get/{id}")//@PathVariable获取路径数据
    private String get(@PathVariable Integer id) {
        return JSON.toJSONString(bookTestService.get(id));
    }

    @GetMapping("/getAll")//@RequestParam 获取key=value数据
    private String getAll(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<BookTest> all = bookTestService.getAll(1);
        return JSON.toJSONString(all);
    }
}

The second way of using PageHelpere:

Introduce dependencies:

 <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>4.0.0</version>
        </dependency>

Injecting pagehelper is not tested:

@Bean
    PageHelper pageHelper(){
        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);

        //添加插件
        new SqlSessionFactoryBean().setPlugins(new Interceptor[]{pageHelper});
        return pageHelper;
    }

 

Service: 

Multi-condition query: the use of xxxExample

Paging return value: Page<T>

@Service
public class BookTestServiceImp implements BookTestService {

    @Autowired
    BookTestDao bookTestDao;

    @Override
    public BookTest get(Integer id) {
        return bookTestDao.selectByPrimaryKey(id);
    }

    @Override
    public Page<BookTest> getAll(Integer id) {
        BookTestExample bookTestExample = new BookTestExample();
        bookTestExample.createCriteria().andIdGreaterThanOrEqualTo(id);
        bookTestExample.setOrderByClause("id DESC");
        return bookTestDao.selectByExample(bookTestExample);
    }
}

 

 

Guess you like

Origin blog.csdn.net/xiangwang2016/article/details/106601668