SpringBoot学习历程(九):SpringBoot2.X集成mybatis和pagehelper分页

本人所用SpringBoot版本为2.1.9.RELEASE

1. 引入相关依赖

<!-- 引入mybatis依赖 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>
<!-- 分页插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.9</version>
</dependency>
<!-- 引入mysql依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

点此 查看阿里仓库各依赖的最新版本

2. 增加datasource配置信息

在application.yml文件中增加:

spring:
  datasource:
    #数据库访问配置
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  returnPageInfo: check
  
mybatis:
  type-aliases-package: com.xj.demo.entity # 注意:对应实体类的路径
  mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径

3. 创建用户信息类

3.1 User.java

这里我用了lombok注解

package com.xj.demo.entity;

import lombok.Data;

import java.io.Serializable;

/**
 * @Description:
 * @Author: RabbitsInTheGrass_xj
 * @Date: 2019/10/1 20:35
 */
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 793100833087044040L;

    private Integer id;
    private String userName;
    private String userPsw;
    private String idCard;
    private String phone;
    private String address;
    private Integer state;
}

3.2 UserMapper.java

package com.xj.demo.dao;

import com.xj.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Description:
 * @Author: RabbitsInTheGrass_xj
 * @Date: 2019/10/1 20:39
 */
@Mapper
public interface UserMapper {

    /**
     * @Description 新增用户信息
     * @Param [record] 用户信息
     * @return int
     **/
    int insert(User record);

    /**
     * @Description 根据主键id查询用户信息
     * @Param id 键ID
     * @return User用户信息
     **/
    User selectByPrimaryKey(Integer id);

    /**
     * @Description 根据主键id更新用户信息
     * @Param [record] 用户
     * @return int
     **/
    int updateByPrimaryKey(User record);

    /**
     * @Description 根据主键id删除用户信息
     * @Param [id] 主键id
     * @return int
     **/
    int deleteByPrimaryKey(Integer id);

    /**
     * @Description 查询用户信息列表
     * @return 用户信息列表
     **/
    List<User> selectAll();
}

3.3 UserMapper.xml

==mybatis.mapper-locations=classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径==
在resource目录下新建mapper目录,创建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.xj.demo.dao.UserMapper" >
    <resultMap id="UserMap" type="com.xj.demo.entity.User" >
        <id property="id"  column="ID" jdbcType="INTEGER" />
        <result property="userName"  column="USER_NAME" jdbcType="VARCHAR" />
        <result property="userPsw" column="USER_PSW" jdbcType="VARCHAR" />
        <result property="idCard" column="ID_CARD" jdbcType="VARCHAR" />
        <result property="phone" column="PHONE" jdbcType="VARCHAR" />
        <result property="address" column="ADDRESS" jdbcType="VARCHAR" />
        <result property="state" column="STATE" jdbcType="INTEGER" />
    </resultMap>

    <insert id="insert" parameterType="com.xj.demo.entity.User" >
        insert into sys_user (ID, USER_NAME, USER_PSW, ID_CARD, PHONE, ADDRESS, STATE)
        values (#{id,jdbcType=INTEGER},
            #{userName,jdbcType=VARCHAR}, #{userPsw,jdbcType=VARCHAR}, #{idCard,jdbcType=VARCHAR},
            #{phone,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, #{state,jdbcType=INTEGER})
    </insert>

    <select id="selectAll" resultMap="UserMap" >
        SELECT
            t.ID,
            t.USER_NAME,
            t.USER_PSW,
            t.ID_CARD,
            t.PHONE,
            t.ADDRESS,
            t.state
        FROM sys_user t
    </select>

    <select id="selectByPrimaryKey" resultMap="UserMap" parameterType="java.lang.Integer" >
        SELECT
            t.ID,
            t.USER_NAME,
            t.USER_PSW,
            t.ID_CARD,
            t.PHONE,
            t.ADDRESS,
            t.STATE
        FROM sys_user t
        where t.ID = #{id,jdbcType=INTEGER}
    </select>

    <update id="updateByPrimaryKey" parameterType="com.xj.demo.entity.User" >
        update sys_user
        set t.USER_NAME = #{userName,jdbcType=VARCHAR},
          t.USER_PSW = #{userPsw,jdbcType=VARCHAR},
          t.ID_CARD = #{idCard,jdbcType=VARCHAR},
          t.PHONE = #{phone,jdbcType=VARCHAR},
          t.ADDRESS = #{address,jdbcType=VARCHAR},
          t.STATE = #{state,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
  </update>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from sys_user t where t.id = #{id,jdbcType=INTEGER}
    </delete>
</mapper>

3.4 UserService.java

package com.xj.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xj.demo.dao.UserMapper;
import com.xj.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: RabbitsInTheGrass_xj
 * @Date: 2019/10/1 21:12
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * @Description 分页查询用户信息
     * @Param [pageNum, pageSize] 分页信息
     * @return com.github.pagehelper.PageInfo<com.xj.demo.entity.User>
     **/
    public PageInfo<User> selectAll(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectAll();
        return new PageInfo<>(userList);
    }

    /**
     * @Description 新增用户
     * @Param [user] 用户信息
     * @return int
     **/
    public int addUser(User user) {
        return userMapper.insert(user);
    }

    /**
     * @Description 更新用户信息
     * @Param [user] 用户
     * @return int
     **/
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    /**
     * @Description 根据ID删除用户
     * @Param [userId] 用户ID
     * @return int
     **/
    public int deleteUser(int userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }

    /**
     * @Description 根据用户ID查询用户
     * @Param [userId] 用户ID
     * @return com.xj.demo.entity.User
     **/
    public User selectByPrimaryKey(int userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}

3.5 UserController.java

package com.xj.demo.controller;

import com.xj.demo.entity.User;
import com.xj.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 用户信息
 * @Author: RabbitsInTheGrass_xj
 * @Date: 2019/10/1 09:31
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/selectAllUser")
    @ResponseBody
    public Object selectAll(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
                            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
        logger.info("============查询所有用户=======");
        return userService.selectAll(pageNum, pageSize);
    }

    @PostMapping("/addUser")
    @ResponseBody
    public int addUser(User user) {
        return userService.addUser(user);
    }

    @PostMapping("/updateUser")
    @ResponseBody
    public int updateUser(User user) {
        return userService.updateUser(user);
    }

    @PostMapping("/deleteUser")
    @ResponseBody
    public int deleteUser(User user) {
        return userService.deleteUser(user.getId());
    }
}

4. 启动类增加注解

package com.xj.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author RabbitsInTheGrass_xj
 */
@MapperScan("com.xj.demo.dao")
@EnableSwagger2
@SpringBootApplication
public class DemoApplication {

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

}

==注意:@MapperScan("com.xj.demo.dao")对应了项目中mapper所对应的包路径==

5. 启动进行测试

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容