(4)学习SpringBoot之整合 Mybatis+PageHelper分页

来源:互联网 发布:在线c语言编程器 编辑:程序博客网 时间:2024/06/06 16:57

1.pom.xml代码,引入相关的依赖包。

<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><!--引入父标签 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.7.RELEASE</version></parent><groupId>cn.moye</groupId><artifactId>spring-boot-mybatis1</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-mybatis1</name><url>http://maven.apache.org</url><dependencies><!-- web 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 引入mysql 数据库 驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- SpringBoot mybatis依赖 --><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>        <!-- json解析依赖 -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>fastjson</artifactId>            <version>1.2.31</version>        </dependency>        <!-- Junit测试依赖包 -->        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><!-- maven插件 --><properties><jdk.version>1.8</jdk.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><build><finalName>spring-boot-mybatis1</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><srouce>${jdk.version}</srouce><target>${jdk.version}</target><encoed>${project.build.sourceEncoding}</encoed></configuration></plugin></plugins></build></project>



2.编写SpringBoot控制器类,在此之前,请先右键Maven项目 Maven --> Update Object 。做过的可以忽略。个人喜欢把App.java改成StartSpringBootMain.java


package cn.moye.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** *  * SpringBoot启动类 * @MapperScan 这个注释可以扫描Mapper持久化类 *  看个人喜好是否使用, *  第二种选择可以在Mapper类上加@Mapper注解 */@SpringBootApplicationpublic class StartSpringBootMain {    public static void main( String[] args )    {    SpringApplication.run(StartSpringBootMain.class,args);    }}



3.建立实体类User,之前在数据库中已经建立了对应的表

package cn.moye.springboot.model;import java.util.Date;/** *  * 实体类User */public class User {private long id;private String username;private String pwd;private Date regtime;public User(long id, String username, String pwd, Date regtime) {super();this.id = id;this.username = username;this.pwd = pwd;this.regtime = regtime;}public User() {super();// TODO Auto-generated constructor stub}public long getId() {return id;}public String getUsername() {return username;}public String getPwd() {return pwd;}public Date getRegtime() {return regtime;}public void setId(long id) {this.id = id;}public void setUsername(String username) {this.username = username;}public void setPwd(String pwd) {this.pwd = pwd;}public void setRegtime(Date regtime) {this.regtime = regtime;}}



4.新建一个src/main/resources资源包,然后建立配置文件application.properties

# mysql的数据库配置#########################################################spring.datasource.url=jdbc:mysql://localhost:3306/testjdbc?characterEncoding=utf8&useSSL=true#spring.datasource.url=jdbc:mysql://localhost:3306/testjdbc?characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver#mybatis#entity扫描的包名mybatis.type-aliases-package=cn.moye.springboot.model#Mapper.xml所在的位置#mybatis.mapper-locations=classpath*:/mybaits/*Mapper.xmlmybatis.mapper-locations=classpath*:cn/moye/springboot/mapper/*Mapper.xml#pagehelper分页插件配置pagehelper.helperDialect=mysqlpagehelper.reasonable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSql



5.新建Dao层 UserMapper类和UserMapper.xml


package cn.moye.springboot.mapper;import java.util.List;import org.apache.ibatis.annotations.Mapper;import cn.moye.springboot.model.User;/* * Dao层 Mapper类 */@Mapperpublic interface UserMapper {/*获取所有数据*/public List<User> getAll();/*查询 根据id*/public User getById(long id);/*新增*/public int insert(User user);/*删除*/public int delete(long id);}


<?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="cn.moye.springboot.mapper.UserMapper"><resultMap id="BaseResultMap" type="cn.moye.springboot.model.User"><id column="ID" property="id" jdbcType="INTEGER" /><result column="username" property="username" jdbcType="VARCHAR" /><result column="pwd" property="pwd" jdbcType="VARCHAR" /><result column="regtime" property="regtime" jdbcType="TIMESTAMP" /></resultMap><sql id="Base_Column_List">id,username,pwd,regtime</sql><select id="getAll" resultMap="BaseResultMap">select<include refid="Base_Column_List" />from t_user</select><select id="getById" resultType="cn.moye.springboot.model.User">select<include refid="Base_Column_List" />from t_user where id = #{id,jdbcType=INTEGER}</select><insert id="insert" parameterType="cn.moye.springboot.model.User">insert into t_user(username,pwd,regtime)values (#{username,jdbcType=VARCHAR},#{pwd,jdbcType=VARCHAR},#{regtime})</insert><delete id="delete" parameterType="LONG">delete from t_user where id = #{id}</delete></mapper>




6.创建UserService.java 类

package cn.moye.springboot.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import cn.moye.springboot.mapper.UserMapper;import cn.moye.springboot.model.User;@Servicepublic class UserService {@Autowiredprivate UserMapper userMapper;/* 获取所有数据 */public List<User> getAll() {return userMapper.getAll();}/* 查询 根据id */public User getById(long id) {return userMapper.getById(id);}/* 新增 */public int insert(User user) {return userMapper.insert(user);}/* 删除 */public int delete(long id) {return userMapper.delete(id);}}

7.创建UserController.java控制类

package cn.moye.springboot.controller;import java.util.Date;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import cn.moye.springboot.model.User;import cn.moye.springboot.service.UserService;@RestControllerpublic class UserController {@Autowiredprivate UserService userService;// @RequestMapping("/getAll")// public List<User> getAll() {// return userService.getAll();// }@RequestMapping("/getAll")@SuppressWarnings("all")public PageInfo<User> getAll(String pageNum, String pageSize) {int num = 1, size = 20;if (!StringUtils.isEmpty(pageNum)) {num = Integer.valueOf(pageNum);}if (!StringUtils.isEmpty(pageSize)) {size = Integer.valueOf(pageSize);}PageHelper.startPage(num, size);PageInfo<User> pagehelper = new PageInfo<User>(userService.getAll());pagehelper.setFirstPage(1);Integer lastPageNum = 0;if (pagehelper.getTotal() % size == 0) {lastPageNum = (int) pagehelper.getTotal() / size;} else {lastPageNum = (int) pagehelper.getTotal() / size + 1;}pagehelper.setLastPage(lastPageNum);return pagehelper;}@RequestMapping("/getById")public User getById(long id) {return userService.getById(id);}@RequestMapping("/insert")public int insert() {User user = new User();user.setUsername("测试Springboot");user.setPwd("123456");user.setRegtime(new Date());return userService.insert(user);}@RequestMapping("/delete")public int delete(long id) {return userService.delete(id);}}




8.测试结果

未加分页



加分页






阅读全文
0 0