欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot+Mybatis+Pagehelper分頁實(shí)現(xiàn)

 更新時(shí)間:2020年08月26日 10:06:18   作者:xiaolyuh123  
本篇文章主要講述的是Spring Boot+Mybatis+Pagehelper分頁實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Spring Boot 集成MyBatis和Pagehelper分頁插件

mybatis-spring-boot-starter依賴樹如下:

pom配置

<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.xiaolyuh</groupId>
  <artifactId>spring-boot-student-mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>spring-boot-student-mybatis</name>

  <!-- 添加Spring Boot的父類依賴,這樣當(dāng)前項(xiàng)目就是Spring Boot項(xiàng)目了。 spring-boot-starter-parent是一個(gè)特殊的starter,他用來
    提供相關(guān)的maven默認(rèn)依賴, 使用它之后,常用的依賴可以省去version標(biāo)簽 -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.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</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!--pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.1.1</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.31</version>
    </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.properties配置

server.port=80
# 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://localhost:3306/ssb_test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#連接池配置
#spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource

#mybatis
#entity掃描的包名
mybatis.type-aliases-package=com.xiaolyuh.domain.model
#Mapper.xml所在的位置
mybatis.mapper-locations=classpath*:/mybaits/*Mapper.xml

#pagehelper分頁插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

#日志配置
logging.level.com.xiaolyuh=debug
logging.level.org.springframework.web=debug
logging.level.org.springframework.transaction=debug
logging.level.org.mybatis=debug

debug=false

除了上面常見的兩項(xiàng)配置,還有:

mybatis.config-location=mybatis-config.xml配置文件的路徑
mybatis.type-handlers-package=掃描typeHandlers的包
mybatis.check-config-location=檢查配置文件是否存在
mybatis.executor-type=設(shè)置執(zhí)行模式(SIMPLE, REUSE, BATCH),默認(rèn)為SIMPLE

Mapping XML文件

在resources文件夾下創(chuàng)建mybaits/PersonMapper.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.xiaolyuh.domain.mapper.PersonMapper" >
 <resultMap id="BaseResultMap" type="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  <id column="id" property="id" jdbcType="BIGINT" />
  <result column="name" property="name" jdbcType="VARCHAR" />
  <result column="age" property="age" jdbcType="INTEGER" />
  <result column="address" property="address" jdbcType="VARCHAR" />
 </resultMap>
 <sql id="Base_Column_List" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  id, name, age, address
 </sql>
 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  select 
  <include refid="Base_Column_List" />
  from person
  where id = #{id,jdbcType=BIGINT}
 </select>
 <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  delete from person
  where id = #{id,jdbcType=BIGINT}
 </delete>
 <insert id="insert" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
   SELECT LAST_INSERT_ID()
  </selectKey>
  insert into person (name, age, address
   )
  values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{address,jdbcType=VARCHAR}
   )
 </insert>
 <insert id="insertSelective" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
   SELECT LAST_INSERT_ID()
  </selectKey>
  insert into person
  <trim prefix="(" suffix=")" suffixOverrides="," >
   <if test="name != null" >
    name,
   </if>
   <if test="age != null" >
    age,
   </if>
   <if test="address != null" >
    address,
   </if>
  </trim>
  <trim prefix="values (" suffix=")" suffixOverrides="," >
   <if test="name != null" >
    #{name,jdbcType=VARCHAR},
   </if>
   <if test="age != null" >
    #{age,jdbcType=INTEGER},
   </if>
   <if test="address != null" >
    #{address,jdbcType=VARCHAR},
   </if>
  </trim>
 </insert>
 <update id="updateByPrimaryKeySelective" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  update person
  <set >
   <if test="name != null" >
    name = #{name,jdbcType=VARCHAR},
   </if>
   <if test="age != null" >
    age = #{age,jdbcType=INTEGER},
   </if>
   <if test="address != null" >
    address = #{address,jdbcType=VARCHAR},
   </if>
  </set>
  where id = #{id,jdbcType=BIGINT}
 </update>
 <update id="updateByPrimaryKey" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  update person
  set name = #{name,jdbcType=VARCHAR},
   age = #{age,jdbcType=INTEGER},
   address = #{address,jdbcType=VARCHAR}
  where id = #{id,jdbcType=BIGINT}
 </update>

 <select id="findAll" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from person
 </select>

 <select id="findByPage" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from person
 </select>
</mapper>

DAO層Mapper類

在Mapper接口上需要加上@Mapper注解,@Mapper注解聲明成mybatis Dao層的Bean。也可以在配置類上使用@MapperScan("com.xiaolyuh.domain.mapper")注解聲明。

package com.xiaolyuh.domain.mapper;

import com.github.pagehelper.Page;
import com.xiaolyuh.domain.model.Person;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper//聲明成mybatis Dao層的Bean,也可以在配置類上使用@MapperScan("com.xiaolyuh.domain.mapper")注解聲明
public interface PersonMapper {

  int deleteByPrimaryKey(Long id);

  int insert(Person record);

  int insertSelective(Person record);

  Person selectByPrimaryKey(Long id);

  int updateByPrimaryKeySelective(Person record);

  int updateByPrimaryKey(Person record);

  /**
   * 獲取所有數(shù)據(jù)
   * @return
   */
  List<Person> findAll();

  /**
   * 分頁查詢數(shù)據(jù)
   * @return
   */
  Page<Person> findByPage();
}

實(shí)體類

package com.xiaolyuh.domain.model;

public class Person {

  private Long id;

  /**
   * 名稱
   */
  private String name;

  /**
   * 年齡
   */
  private Integer age;

  /**
   * 地址
   */
  private String address;

  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 Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }
}

Service層

接口

package com.xiaolyuh.service;

import com.github.pagehelper.Page;
import com.xiaolyuh.domain.model.Person;

import java.util.List;

/**
 * Created by yuhao.wang on 2017/6/19.
 */
public interface PersonService {

  List<Person> findAll();

  /**
   * 分頁查詢
   * @param pageNo 頁號(hào)
   * @param pageSize 每頁顯示記錄數(shù)
   * @return
   */
  Page<Person> findByPage(int pageNo, int pageSize);

  void insert(Person person);
}

實(shí)現(xiàn)類

package com.xiaolyuh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaolyuh.domain.mapper.PersonMapper;
import com.xiaolyuh.domain.model.Person;
import com.xiaolyuh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by yuhao.wang on 2017/6/19.
 */
@Service
@Transactional(readOnly = true)
public class PersonServiceImpl implements PersonService {

  @Autowired
  private PersonMapper personMapper;

  @Override
  public List<Person> findAll() {
    return personMapper.findAll();
  }

  @Override
  public Page<Person> findByPage(int pageNo, int pageSize) {
    PageHelper.startPage(pageNo, pageSize);
    return personMapper.findByPage();
  }

  @Override
  @Transactional
  public void insert(Person person) {
    personMapper.insert(person);
  }

}

分頁的包裝類PageInfo

需要把Page包裝成PageInfo對(duì)象才能序列化。該插件也默認(rèn)實(shí)現(xiàn)了一個(gè)PageInfo

package com.xiaolyuh.page;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import com.github.pagehelper.Page;

/**
 * 對(duì)Page<E>結(jié)果進(jìn)行包裝
 * <p/>
 * 新增分頁的多項(xiàng)屬性,主要參考:http://bbs.csdn.net/topics/360010907
 *
 * @author liuzh/abel533/isea533
 * @version 3.3.0
 * @since 3.2.2
 * 項(xiàng)目地址 : http://git.oschina.net/free/Mybatis_PageHelper
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class PageInfo<T> implements Serializable {
  private static final long serialVersionUID = 1L;
  //當(dāng)前頁
  private int pageNum;
  //每頁的數(shù)量
  private int pageSize;
  //總記錄數(shù)
  private long total;
  //總頁數(shù)
  private int pages;
  //結(jié)果集
  private List<T> list;
  //是否為第一頁
  private boolean isFirstPage = false;
  //是否為最后一頁
  private boolean isLastPage = false;


  public PageInfo() {
  }

  /**
   * 包裝Page對(duì)象
   *
   * @param list
   */
  public PageInfo(List<T> list) {
    if (list instanceof Page) {
      Page page = (Page) list;
      this.pageNum = page.getPageNum();
      this.pageSize = page.getPageSize();

      this.pages = page.getPages();
      this.list = page;
      this.total = page.getTotal();
    } else if (list instanceof Collection) {
      this.pageNum = 1;
      this.pageSize = list.size();

      this.pages = 1;
      this.list = list;
      this.total = list.size();
    }
    if (list instanceof Collection) {
      //判斷頁面邊界
      judgePageBoudary();
    }
  }

  /**
   * 判定頁面邊界
   */
  private void judgePageBoudary() {
    isFirstPage = pageNum == 1;
    isLastPage = pageNum == pages;
  }

  public int getPageNum() {
    return pageNum;
  }

  public void setPageNum(int pageNum) {
    this.pageNum = pageNum;
  }

  public int getPageSize() {
    return pageSize;
  }

  public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
  }

  public long getTotal() {
    return total;
  }

  public void setTotal(long total) {
    this.total = total;
  }

  public int getPages() {
    return pages;
  }

  public void setPages(int pages) {
    this.pages = pages;
  }

  public List<T> getList() {
    return list;
  }

  public void setList(List<T> list) {
    this.list = list;
  }

  public boolean isIsFirstPage() {
    return isFirstPage;
  }

  public void setIsFirstPage(boolean isFirstPage) {
    this.isFirstPage = isFirstPage;
  }

  public boolean isIsLastPage() {
    return isLastPage;
  }

  public void setIsLastPage(boolean isLastPage) {
    this.isLastPage = isLastPage;
  }

  @Override
  public String toString() {
    final StringBuffer sb = new StringBuffer("PageInfo{");
    sb.append("pageNum=").append(pageNum);
    sb.append(", pageSize=").append(pageSize);
    sb.append(", total=").append(total);
    sb.append(", pages=").append(pages);
    sb.append(", list=").append(list);
    sb.append(", isFirstPage=").append(isFirstPage);
    sb.append(", isLastPage=").append(isLastPage);
    sb.append(", navigatepageNums=");
    sb.append('}');
    return sb.toString();
  }
}

測(cè)試類

package com.xiaolyuh;

import com.github.pagehelper.Page;
import com.xiaolyuh.domain.model.Person;
import com.xiaolyuh.page.PageInfo;
import com.xiaolyuh.service.PersonService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonMapperTests {

 private Logger logger = LoggerFactory.getLogger(PersonMapperTests.class);

 @Autowired
 private PersonService personService;

 @Before
 public void testInsert() {
 Person person = new Person();
 person.setName("測(cè)試");
 person.setAddress("address");
 person.setAge(10);
 personService.insert(person);

 Assert.assertNotNull(person.getId());
 logger.debug(JSON.toJSONString(person));
 }

 @Test
 public void testFindAll() {
 List<Person> persons = personService.findAll();

 Assert.assertNotNull(persons);
 logger.debug(JSON.toJSONString(persons));
 }

 @Test
 public void testFindByPage() {
 Page<Person> persons = personService.findByPage(1, 2);
 // 需要把Page包裝成PageInfo對(duì)象才能序列化。該插件也默認(rèn)實(shí)現(xiàn)了一個(gè)PageInfo
 PageInfo<Person> pageInfo = new PageInfo<>(persons);
 Assert.assertNotNull(persons);
 logger.debug(pageInfo.toString());
 logger.debug(JSON.toJSONString(pageInfo));
 }

 @Test
 public void testCacheByPage() {
 long begin = System.currentTimeMillis();
 List<Person> persons = personService.findAll();
 long ing = System.currentTimeMillis();
 personService.findAll();
 long end = System.currentTimeMillis();
 logger.debug("第一次請(qǐng)求時(shí)間:" + (ing - begin) + "ms");
 logger.debug("第二次請(qǐng)求時(shí)間:" + (end - ing) + "ms");

 Assert.assertNotNull(persons);
 logger.debug(persons.toString());
 logger.debug(JSON.toJSONString(persons));
 }

}

源碼

https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

到此這篇關(guān)于Spring Boot+Mybatis+Pagehelper分頁實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Spring Boot+Mybatis+Pagehelper分頁內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring?Boot?多數(shù)據(jù)源處理事務(wù)的思路詳解

    Spring?Boot?多數(shù)據(jù)源處理事務(wù)的思路詳解

    這篇文章主要介紹了Spring?Boot?多數(shù)據(jù)源如何處理事務(wù),本文單純就是技術(shù)探討,要從實(shí)際應(yīng)用中來說的話,我并不建議這樣去玩分布式事務(wù)、也不建議這樣去玩多數(shù)據(jù)源,畢竟分布式事務(wù)主要還是用在微服務(wù)場(chǎng)景下,對(duì)Spring?Boot?多數(shù)據(jù)源事務(wù)相關(guān)知識(shí)感興趣的朋友參考下本文
    2022-06-06
  • 基于springboot redirect重定向路徑問題總結(jié)

    基于springboot redirect重定向路徑問題總結(jié)

    這篇文章主要介紹了springboot redirect重定向路徑問題總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • JAVA位運(yùn)算的知識(shí)點(diǎn)總結(jié)

    JAVA位運(yùn)算的知識(shí)點(diǎn)總結(jié)

    在本篇文章里小編給大家整理的是關(guān)于JAVA有關(guān)位運(yùn)算的全套梳理,需要的朋友們可以參考學(xué)習(xí)下。
    2020-03-03
  • 舉例講解Java的Jackson庫中ObjectMapper類的使用

    舉例講解Java的Jackson庫中ObjectMapper類的使用

    這篇文章主要介紹了舉例講解Java的Jackson庫中ObjectMapper類的使用,Jackson庫通常被用來實(shí)現(xiàn)Java的對(duì)象和JSON之間的轉(zhuǎn)換功能,需要的朋友可以參考下
    2016-01-01
  • 淺析Java中的異常處理機(jī)制

    淺析Java中的異常處理機(jī)制

    這篇文章主要介紹了Java中的異常處理機(jī)制的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)Java,感興趣的朋友可以了解下
    2020-11-11
  • 使用springboot跳轉(zhuǎn)到指定頁面和(重定向,請(qǐng)求轉(zhuǎn)發(fā)的實(shí)例)

    使用springboot跳轉(zhuǎn)到指定頁面和(重定向,請(qǐng)求轉(zhuǎn)發(fā)的實(shí)例)

    這篇文章主要介紹了使用springboot跳轉(zhuǎn)到指定頁面和(重定向,請(qǐng)求轉(zhuǎn)發(fā)的實(shí)例),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • JAVA中IP和整數(shù)相互轉(zhuǎn)化的方法

    JAVA中IP和整數(shù)相互轉(zhuǎn)化的方法

    這篇文章主要介紹了JAVA中IP和整數(shù)相互轉(zhuǎn)化的方法,涉及java數(shù)值轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • 深入理解Java中@Accessors和@Builder

    深入理解Java中@Accessors和@Builder

    本文主要介紹了@Accessors和@Builder使用,區(qū)別與坑,對(duì)使用這兩個(gè)注解的有一定的幫助,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-08-08
  • JVM完全解讀之Metaspace解密源碼分析

    JVM完全解讀之Metaspace解密源碼分析

    通過這篇文章,你將可以了解到,為什么會(huì)有metaspace?metaspace的組成,metaspace的VM參數(shù),jstat里我們應(yīng)該關(guān)注metaspace的哪些值,有需要的朋友可以借鑒參考下
    2022-01-01
  • 如何使用IDEA2022.1?創(chuàng)建Spring?Boot項(xiàng)目

    如何使用IDEA2022.1?創(chuàng)建Spring?Boot項(xiàng)目

    這篇文章主要介紹了如何使用IDEA2022.1?創(chuàng)建Spring?Boot項(xiàng)目,大家在使用idea開發(fā)工具時(shí)發(fā)現(xiàn)給以往的版本略微的不同,細(xì)心的小編在此記錄下,需要的朋友可以參考下
    2022-08-08

最新評(píng)論