欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis+MyBatisGenerator+PageHelper集成

程序员文章站 2022-05-26 11:02:04
...

初始化一个web项目mybatis_test,pom文件如下所示:

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">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.haiyoung</groupId>
	<artifactId>mybatis_test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mybatis_test</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<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-jdbc</artifactId>
		</dependency>
		<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>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.6</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
application.yml配置文件
spring:
  #数据库配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/haiyoung?useSSL=true&serverTimezone=UTC
    username: root
    password: xxxxxx #thinkpad
#    password: xxxxxx #mint
server:
  port: 8080
  servlet:
    context-path: /mybatis_test
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  config-location: classpath:mybatis-config.xml
mybatis-config.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!--指定mybatis所用日志的具体实现,未指定时将自动查找-->
        <!--打印sql-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <!--指定一个包名,mybatis会在包名下面搜索Java Bean-->
        <package name="com.haiyoung.model"/>
    </typeAliases>

</configuration>

mybatis集成MyBatisGenerator

添加 mybatis-generator-core 依赖
<!--mybatis-generator-->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>
添加 mybatis-generator-maven-plugin 插件配置到pom文件中
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.5</version>
    <!--mybatis_generator配置文件位置-->
    <configuration>
        <configurationFile>src/main/resources/mybatis_generator_config.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
</plugin>
mybatis-generator配置文件mybatis_generator_config.xml
<?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>
    <!--连接数据库驱动的位置-->
    <classPathEntry location="C:\Users\Think\.m2\repository\mysql\mysql-connector-java\6.0.6\mysql-connector-java-6.0.6.jar" />

    <context id="mysqlContext" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="false"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--mysql数据库连接-->
        <!--nullCatalogMeansCurrent=true这个参数是特地为解决catalog异常问题而配置的-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/haiyoung?useSSL=true&serverTimezone=UTC&nullCatalogMeansCurrent=true"
                        userId="root"
                        password="xxxxxx">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--model生成目录-->
        <javaModelGenerator targetPackage="com.haiyoung.model" targetProject="src\main\java">
            <property name="enableSubPackages" value="false" /><!--是否让schema作为包的后缀-->
            <property name="trimStrings" value="true" /><!--从数据库返回的值是否清理前后的空格-->
        </javaModelGenerator>

        <!--mapper.xml生成目录-->
        <sqlMapGenerator targetPackage="mapper"  targetProject="src\main\resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!--接口生成目录-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.haiyoung.mapper"  targetProject="src\main\java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!--table-->
        <table schema="haiyoung" tableName="person" domainObjectName="Person"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <!--catalog="haiyoung"-->
            <!--解决Cannot obtain primary key information from 的问题-->
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        </table>
    </context>
</generatorConfiguration>
运行mybatis-generator:generate自动生成mapper.xml文件及接口
Mybatis+MyBatisGenerator+PageHelper集成
生成的文件如下图所示:
Mybatis+MyBatisGenerator+PageHelper集成
经测试,生成文件自动关联,运行时也没有什么异常
向数据库中添加如下测试数据

Mybatis+MyBatisGenerator+PageHelper集成

测试其中一个根据id获取数据的接口如下所示:

@RequestMapping("/person")
public Person getPerson(HttpServletRequest request,
       @RequestParam(value = "id") Integer id){
    return personService.getPerson(id);
}

public Person getPerson(Integer id){
    return personMapper.selectByPrimaryKey(id);
}

当id=3时,返回结果如下图所示:

http://localhost:8080/mybatis_test/person?id=3

返回结果如下所示:

{
    "id": 3,
    "name": "xxx",
    "age": 18,
    "description": "xxxxx"
}
mybatis-generator配置成功,工作正常

mybatis集成PageHelper

pom文件中添加如下依赖
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.4</version>
</dependency>

mybatis-config.xml文件中添加pageHelper拦截器插件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!--指定mybatis所用日志的具体实现,未指定时将自动查找-->
        <!--打印sql-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <!--指定一个包名,mybatis会在包名下面搜索Java Bean-->
        <package name="com.haiyoung.model"/>
    </typeAliases>

    <!--配置pageHelper拦截器插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用下面的方式配置参数-->
            <!-- 配置分页插件使用哪种方言,此处配置mysql-->
            <property name="helperDialect" value="mysql"/>
            <!--offsetAsPageNum:默认值为 false,该参数对使用 RowBounds 作为分页参数时有效。
            当该参数设置为 true 时,会将 RowBounds 中的 offset 参数当成 pageNum 使用,
            可以用页码和页面大小两个参数进行分页。-->
            <property name="offsetAsPageNum" value="false"/>
            <!--rowBoundsWithCount:默认值为false,该参数对使用 RowBounds 作为分页参数时有效。
            当该参数设置为true时,使用 RowBounds 分页会进行 count 查询-->
            <property name="rowBoundsWithCount" value="false"/>
            <!--pageSizeZero:默认值为 false,当该参数设置为 true 时,
            如果 pageSize=0 或者 RowBounds.limit = 0 就会查询出全部的结果
            (相当于没有执行分页查询,但是返回结果仍然是 Page 类型)-->
            <property name="pageSizeZero" value="true"/>
            <!--reasonable:分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页,
            pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询-->
            <property name="reasonable" value="false"/>
            <!--supportMethodsArguments:支持通过 Mapper 接口参数来传递分页参数,默认值false,
            分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,
            查找到合适的值时就会自动分页。 使用方法可以参考测试代码中的
            com.github.pagehelper.test.basic 包下的 ArgumentsMapTest 和 ArgumentsObjTest-->
            <property name="supportMethodsArguments" value="false"/>
            <!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
            <property name="returnPageInfo" value="none"/>
        </plugin>
    </plugins>

</configuration>

新建一个Mapped URL如下所示:

@RequestMapping("/allPersons")
public List<Person> getPerson(HttpServletRequest request){
    return personService.getAllPersons();
}

@RequestMapping("/page/allPersons")
public PageInfo<List<Person>> getPersonByPage(HttpServletRequest request,
       @RequestParam(value = "pageNum") Integer pageNum,
       @RequestParam(value = "pageSize") Integer pageSize){
//        PageHelper.startPage(1, 5);
    PageHelper.startPage(pageNum, pageSize);
    //紧跟着的第一个select方法会被分页
    List<Person> persons = personService.getAllPersons();
    PageInfo page = new PageInfo(persons);
    return page;
}
我们测试一下:
首先我们获取所有数据:
http://localhost:8080/mybatis_test/allPersons
返回了所有数据:
[
    {
        "id": 1,
        "name": "Test111",
        "age": 27,
        "description": "Test111"
    },
    {
        "id": 2,
        "name": "Test222",
        "age": 25,
        "description": "Test222"
    },
    {
        "id": 3,
        "name": "xxx",
        "age": 18,
        "description": "xxxxx"
    },
    {
        "id": 4,
        "name": "xxx01",
        "age": 19,
        "description": "xxx01"
    },
    {
        "id": 5,
        "name": "xxx02",
        "age": 20,
        "description": "xxx02"
    },
    {
        "id": 6,
        "name": "xxx03",
        "age": 21,
        "description": "xxx03"
    },
    {
        "id": 7,
        "name": "xxx04",
        "age": 22,
        "description": "xxx04"
    },
    {
        "id": 8,
        "name": "xxx05",
        "age": 23,
        "description": "xxx05"
    }
]
我们再测试一下分页:
http://localhost:8080/mybatis_test/page/allPersons?pageNum=1&pageSize=5
返回第一页5行数据:
{
    "total": 8,
    "list": [
        {
            "id": 1,
            "name": "Test111",
            "age": 27,
            "description": "Test111"
        },
        {
            "id": 2,
            "name": "Test222",
            "age": 25,
            "description": "Test222"
        },
        {
            "id": 3,
            "name": "xxx",
            "age": 18,
            "description": "xxxxx"
        },
        {
            "id": 4,
            "name": "xxx01",
            "age": 19,
            "description": "xxx01"
        },
        {
            "id": 5,
            "name": "xxx02",
            "age": 20,
            "description": "xxx02"
        }
    ],
    "pageNum": 1,
    "pageSize": 5,
    "size": 5,
    "startRow": 1,
    "endRow": 5,
    "pages": 2,
    "prePage": 0,
    "nextPage": 2,
    "isFirstPage": true,
    "isLastPage": false,
    "hasPreviousPage": false,
    "hasNextPage": true,
    "navigatePages": 8,
    "navigatepageNums": [
        1,
        2
    ],
    "navigateFirstPage": 1,
    "navigateLastPage": 2,
    "firstPage": 1,
    "lastPage": 2
}
我们修改一下参数,获取第二页数据:
http://localhost:8080/mybatis_test/page/allPersons?pageNum=2&pageSize=5
返回第二页数据如下所示:
{
    "total": 8,
    "list": [
        {
            "id": 6,
            "name": "xxx03",
            "age": 21,
            "description": "xxx03"
        },
        {
            "id": 7,
            "name": "xxx04",
            "age": 22,
            "description": "xxx04"
        },
        {
            "id": 8,
            "name": "xxx05",
            "age": 23,
            "description": "xxx05"
        }
    ],
    "pageNum": 2,
    "pageSize": 5,
    "size": 3,
    "startRow": 6,
    "endRow": 8,
    "pages": 2,
    "prePage": 1,
    "nextPage": 0,
    "isFirstPage": false,
    "isLastPage": true,
    "hasPreviousPage": true,
    "hasNextPage": false,
    "navigatePages": 8,
    "navigatepageNums": [
        1,
        2
    ],
    "navigateFirstPage": 1,
    "navigateLastPage": 2,
    "firstPage": 1,
    "lastPage": 2
}
至此,我们成功集成了Mybatis+MyBatisGenerator+PageHelper,且能正常工作。
源代码地址:https://github.com/Haiyoung/HyProject/tree/master/mybatis_test