Spring Boot入门教程(四)之Mybatis集成和分页集成

 

myBatis看spring boot这么火热开发出一套解决方案来凑凑热闹,但这一凑确实解决了很多问题,使用起来确实顺畅了许多。mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解解决一切问题,一种是简化后的老传统。

当然任何模式都需要首先引入mybatis-spring-boot-starter的pom文件

    <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>
      <scope>runtime</scope>
    </dependency>

好了下来分别介绍两种开发模式

一、无配置文件注解版

1.目录结构

2 新建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.loafer</groupId>
  <artifactId>springboot03_annotation</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>springboot03_annotation</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--springboot连接数据库-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
  </dependencies>

</project>

2、application.yml 添加相关配置

##端口号设置
server:
  port: 8001
  ##访问项目根路径设置
  servlet:
    context-path: /boot
spring:
  ##数据源配置
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: root
    password: pass
    driver-class-name: com.mysql.jdbc.Driver
##mybatis配置
mybatis:
  type-aliases-package: com.loafer.entity
##配置打印sql
logging:
  level:
    com.loafer.mapper: DEBUG

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。

在启动类中添加对mapper包扫描@MapperScan

@SpringBootApplication
@MapperScan("com.loafer.mapper")
public class StartApplication {

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

或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个mapper加个注解也挺麻烦的

3、开发Mapper

第三步是最关键的一块,sql生产都在这里

package com.loafer.mapper;


import com.loafer.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
    @Select("SELECT * FROM user")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "createTime", column = "createtime")
    })
    public List<User> getUser();

    @Select("SELECT * FROM user WHERE id = #{id}")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "createTime", column = "createtime")
    })
    User getUserById(Long id);

    @Insert("INSERT INTO user(name,createTime) VALUES(#{name}, now())")
    void insert(User user);

    @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id =#{id}")
    void delete(Long id);
}

注解解释:

  • @Select 是查询类的注解,所有的查询均使用这个
  • @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
  • @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
  • @Update 负责修改,也可以直接传入对象
  • @delete 负责删除

controller层代码

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

    @Autowired
    private UserService userService;

    @GetMapping("/get")
    public List<User> getUser(){
        return userService.getUser();
    }

}

运行结果:

完整代码下载地址:https://github.com/loafer7423/springboot/tree/master/springboot03_annotation

二、xml版本

1.目录结构

2.新建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.loafer</groupId>
  <artifactId>springboot03</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springboot03</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--springboot连接数据库-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>

  </dependencies>

</project>

3.application.yml 添加相关配置

##端口号设置
server:
  port: 8001
  ##访问项目根路径设置
  servlet:
    context-path: /boot
spring:
  ##数据源配置
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: root
    password: pass
    driver-class-name: com.mysql.jdbc.Driver
##mybatis配置
mybatis:
  type-aliases-package: com.loafer.entity
  mapper-locations: classpath:mapper/*.xml
##配置打印sql
logging:
  level:
    com.loafer.mapper: DEBUG

4.项目启动入口配置

@MapperScan: 配置dao层或者mapper层, 如果不在Application上配置注解也可以在每个mapper上标注@Mapper也可以,不过这需要在每一个上面都要标注,比较麻烦

@SpringBootApplication
@MapperScan("com.loafer.mapper")
public class StartApplication {

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

5.控制器代码

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

    @Autowired
    private UserService userService;

    @GetMapping("/get")
    public List<User> getUser(){
        return userService.getUser();
    }
}

6.接口和接口实现类

public interface UserService {
    List<User> getUser();
}



@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> getUser() {
        return userMapper.getUser();
    }
}

7.Mapper层

public interface UserMapper {
    public List<User> getUser();
}

8.UserMapper.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="com.loafer.mapper.UserMapper">


    <select id="getUser" resultType="com.loafer.entity.User">
        SELECT * FROM user
    </select>

</mapper>

运行结果:

完整代码下载:https://github.com/loafer7423/springboot/tree/master/springboot03

三、MyBatis集成Druid

1.目录结构

2. 引入依赖

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.14</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

3.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.loafer</groupId>
  <artifactId>springboot03</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springboot03</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--springboot连接数据库-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.14</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
  </dependencies>

</project>

4.配置application.properties

server.port=8001
server.servlet.context-path=/boot
## Mybatis 配置
mybatis.typeAliasesPackage=com.loafer.entity
mybatis.mapperLocations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

# 打印mybatis中的sql语句
logging.level.com.loafer.mapper=debug
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.exceptionSorter=true
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
spring.datasource.useGlobalDataSourceStat=true

5.DruidConfiguration.java

package com.loafer.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class DruidConfiguration {
    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize}")
    private int initialSize;
    @Value("${spring.datasource.minIdle}")
    private int minIdle;
    @Value("${spring.datasource.maxActive}")
    private int maxActive;
    @Value("${spring.datasource.maxWait}")
    private int maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;
    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.filters}")
    private String filters;
    @Value("${spring.datasource.connectionProperties}")
    private String connectionProperties;
    @Value("${spring.datasource.useGlobalDataSourceStat}")
    private boolean useGlobalDataSourceStat;

    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            System.err.println("druid configuration initialization filter: "+ e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
}

6.DruidStatFilter.java

package com.loafer.filter;


import com.alibaba.druid.support.http.WebStatFilter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(filterName="druidWebStatFilter",
        urlPatterns="/*",
        initParams={
                @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"),// 忽略资源
        })
public class DruidStatFilter extends WebStatFilter {

}

7.DruidStatViewServlet.java

package com.loafer.servlet;


import com.alibaba.druid.support.http.StatViewServlet;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(urlPatterns = "/druid/*", initParams={
        @WebInitParam(name="allow",value=""),// IP白名单 (没有配置或者为空,则允许所有访问)
        @WebInitParam(name="deny",value=""),// IP黑名单 (存在共同时,deny优先于allow)
        @WebInitParam(name="loginUsername",value="admin"),// 用户名
        @WebInitParam(name="loginPassword",value="admin"),// 密码
        @WebInitParam(name="resetEnable",value="true")// 禁用HTML页面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {

}

8.项目启动类

package com.loafer;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
@MapperScan("com.loafer.mapper")
public class StartApplication {

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

9.访问http://localhost:8001/boot/druid/login.html并使用admin admin登录

完整代码下载:https://github.com/loafer7423/springboot/tree/master/springboot04

四、分页插件集成PageHelper

MyBatis框架的PageHelper插件,它是一个非常好用的分页插件,通常我们的项目中如果集成了MyBatis的话,只需三步骤,不管是Spring集成还是SpringBoot集成都是老套路。

1.目录结构:

2.pom文件引入依赖

    <!-- 分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.2.5</version>
    </dependency>

pom完整内容

<?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.loafer</groupId>
  <artifactId>springboot05</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>springboot05</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--springboot连接数据库-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- 分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.2.5</version>
    </dependency>
  </dependencies>
</project>

3.修改启动类

@SpringBootApplication
@MapperScan("com.loafer.mapper")
public class StartApplication {

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

}

4.application.yml

##pagehelper分页插件配置
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

完整内容:

##端口号设置
server:
  port: 8001
  ##访问项目根路径设置
  servlet:
    context-path: /boot
spring:
  ##数据源配置
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: root
    password: pass
    driver-class-name: com.mysql.jdbc.Driver
##mybatis配置
mybatis:
  type-aliases-package: com.loafer.entity
  mapper-locations: classpath:mapper/*.xml
##配置打印sql
logging:
  level:
    com.loafer.mapper: DEBUG
##pagehelper分页插件配置
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

5.Controller层

package com.loafer.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.loafer.entity.User;
import com.loafer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

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

    @Autowired
    private UserService userService;

    @GetMapping("/get")
    public List<User> getUser(){
        return userService.getUser();
    }

    @GetMapping("/page")
    public PageInfo<User> page(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<User> pageInfo = new PageInfo<>(userService.findAll());
        return pageInfo;
    }

    @GetMapping("/list")
    public List<User> list(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize) {
        //pageNo和pageSize两个参数是为了接收前台传过来的值,并且通过defaultValue为这两个参数提供了默认值。
        //分页主要代码:PageHelper.startPage(pageNo,pageSize);
        //需要注意的是,分页代码PageHelper.startPage(pageNo,pageSize);只对其后的第一个查询有效。
        // 如把代码改为下面这样,添加一个查询,则第二个查询并没有分页
        PageHelper.startPage(pageNo,pageSize);
        userService.findAll();//这个查询会分页
        return userService.findAll();//这个查询不会分页
    }


}

6.User.java实体类

package com.loafer.entity;

import java.util.Date;

/**
 * @ClassName User
 * @Description [一句话描述做什么]
 * @Author wangdong
 * @Date 2019/6/5 14:01
 * @Version V1.0
 **/
public class User {

    private Long id;

    private String name;

    private Date createTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

7.接口和接口实现类

package com.loafer.service;


import com.github.pagehelper.Page;
import com.loafer.entity.User;

import java.util.List;

public interface UserService {
    List<User> getUser();

    Page<User> findAll();
}




@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> getUser() {
        return userMapper.getUser();
    }

    @Override
    public Page<User> findAll() {
        return userMapper.findAll();
    }
}

8.UserMapper.java

public interface UserMapper {
    public List<User> getUser();

    Page<User> findAll();
}

9.UserMapper.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="com.loafer.mapper.UserMapper">


    <select id="getUser" resultType="com.loafer.entity.User">
        SELECT * FROM user
    </select>

    <select id="findAll" resultType="com.loafer.entity.User">
         SELECT * FROM user
    </select>
</mapper>

10.测试

启动服务,浏览器输入http://localhost:8001/boot/user/page?pageNo=1&pageSize=5,可以看到只查询了第一页5条数据:

运行结果:

{
    "total": 12,
    "list": [
        {
            "id": 1,
            "name": "zhangsan",
            "createTime": "2019-06-05T14:22:21.000+0000"
        },
        {
            "id": 2,
            "name": "lsii",
            "createTime": "2019-06-04T14:22:31.000+0000"
        },
        {
            "id": 3,
            "name": "wangwu1",
            "createTime": "2019-06-10T23:26:02.000+0000"
        },
        {
            "id": 4,
            "name": "wangwu2",
            "createTime": "2019-06-10T23:26:02.000+0000"
        },
        {
            "id": 5,
            "name": "wangwu3",
            "createTime": "2019-06-10T23:26:02.000+0000"
        }
    ],
    "pageNum": 1,
    "pageSize": 5,
    "size": 5,
    "startRow": 1,
    "endRow": 5,
    "pages": 3,
    "prePage": 0,
    "nextPage": 2,
    "isFirstPage": true,
    "isLastPage": false,
    "hasPreviousPage": false,
    "hasNextPage": true,
    "navigatePages": 8,
    "navigatepageNums": [
        1,
        2,
        3
    ],
    "navigateFirstPage": 1,
    "navigateLastPage": 3,
    "firstPage": 1,
    "lastPage": 3
}

浏览器输入http://localhost:8001/boot/user/list?pageNo=1&pageSize=5,则返回

[
    {
        "id": 1,
        "name": "zhangsan",
        "createTime": "2019-06-05T14:22:21.000+0000"
    },
    {
        "id": 2,
        "name": "lsii",
        "createTime": "2019-06-04T14:22:31.000+0000"
    },
    {
        "id": 3,
        "name": "wangwu1",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 4,
        "name": "wangwu2",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 5,
        "name": "wangwu3",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 6,
        "name": "wangwu4",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 7,
        "name": "wangwu5",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 8,
        "name": "wangwu6",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 9,
        "name": "wangwu7",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 10,
        "name": "wangwu8",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 11,
        "name": "wangwu9",
        "createTime": "2019-06-10T23:26:02.000+0000"
    },
    {
        "id": 12,
        "name": "wangwu10",
        "createTime": "2019-06-10T23:26:02.000+0000"
    }
]

完整代码下载:https://github.com/loafer7423/springboot/tree/master/springboot05

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值