转载

SpringBoot教程(四)集成mybatis(druid、分页插件)构建web服务

  • 操作系统:Mac OS X 10.13.2

  • 编辑器:IntelliJ IDEA 2017

  • JDK版本:jdk 1.8

  • Maven版本:apache-maven-3.5.0

  • SpringBoot版本:SpringBoot 2.0

二、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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.lonelycountry</groupId>
	<artifactId>springboot-mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-mybatis</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<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>2.0.0</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 分页插件 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.5</version>
		</dependency>
		<!-- alibaba的druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.9</version>
		</dependency>
	</dependencies>

	<build>
    	<plugins>
    		<plugin>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-maven-plugin</artifactId>
    		</plugin>
    		<!--这个自动生成工具我觉得不好用啊-->
    		<!--<plugin>-->
    			<!--<groupId>org.mybatis.generator</groupId>-->
    			<!--<artifactId>mybatis-generator-maven-plugin</artifactId>-->
    			<!--<version>1.3.2</version>-->
    			<!--<configuration>-->
    				<!--<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>-->
    				<!--<overwrite>true</overwrite>-->
    				<!--<verbose>true</verbose>-->
    			<!--</configuration>-->
    		<!--</plugin>-->
    	</plugins>
	</build>
</project>
复制代码

三、配置文件以及工程结构

1、配置文件

application.yml

spring:
  datasource:
    name: springboot-demo
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      filters: stat
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: ******
      url: jdbc:mysql://localhost:3306/springboot-mybatis
      initial-size: 1
      min-idle: 1
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20
  http:
    encoding:
      charset: UTF-8
server:
  port: 80
  tomcat:
    uri-encoding: utf-8
mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.lonelycountry.springbootmybatis.po
  configuration:
    map-underscore-to-camel-case: true
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql
复制代码

2、目录结构

SpringBoot教程(四)集成mybatis(druid、分页插件)构建web服务

四、编写代码

1、构建Po层以及数据库表

(1)、User类

package com.lonelycountry.springbootmybatis.po;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.apache.ibatis.type.Alias;

import java.sql.Timestamp;

@Alias("User")//设置别名,在mapper.xml里面就不需要每次都填完整路径了
@ToString
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;

    private String username;

    private String password;

    private Integer age;

    private Timestamp createDate;

}
复制代码

(2)、User表

SpringBoot教程(四)集成mybatis(druid、分页插件)构建web服务

2、构建Dao层

package com.lonelycountry.springbootmybatis.dao;

import com.lonelycountry.springbootmybatis.po.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    List<User> listUsers();

    List<User> listUsers(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize);

    User getUser(@Param("id") Long id);

    void insertUser(User user);

    void updateUser(User user);

    void batchInsertUser(@Param("users") List<User> users);

    void deleteUser(@Param("id") Long id);

    void batchDeleteUser(@Param("ids") List<Long> ids);
}
复制代码
<?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.lonelycountry.springbootmybatis.dao.UserMapper">
  <select id="listUsers" resultType="User">
    select * from user
  </select>

  <select id="getUser" resultType="User">
    select * from user
    <where>
      <if test="id != null">
        id = #{id}
      </if>
    </where>
  </select>

  <insert id="insertUser">
    insert into user (id,username,password,age,create_date)
    values (#{id},#{username},#{password},#{age},#{createDate})
  </insert>

  <insert id="batchInsertUser">
    insert into user (id,username,password,age,create_date)
    values
    <foreach collection="users" item="user" index="index" separator=",">
      (#{user.id},#{user.username},#{user.password},#{user.age},#{user.createDate})
    </foreach>
  </insert>

  <update id="updateUser">
    update user
    <set>
      username = #{username},
      password = #{password},
      age = #{age},
      create_date = #{createDate}
    </set>
    <where>
      id = #{id}
    </where>
  </update>
  
  <delete id="deleteUser">
    delete from user
    <where>
      <if test="id != null">
        id = #{id}
      </if>
    </where>
  </delete>

  <delete id="batchDeleteUser">
    delete from user
    <where>
      id in
      <foreach collection="ids" item="id" index="index" separator="," open="(" close=")">
        <if test="id != null">
          #{id}
        </if>
      </foreach>
    </where>
  </delete>
</mapper>
复制代码

说明:

写了通用的增删改查以及部分批量操作。具体请看mybatis官方文档。

3、构建controller层

UserController

package com.lonelycountry.springbootmybatis.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lonelycountry.springbootmybatis.dao.UserMapper;
import com.lonelycountry.springbootmybatis.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;

/**
 * @author zhuqiwei
 * 2019-02-19.
 */
@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("/user/all")
    public List<User> getUser() {
        List<User> users = userMapper.listUsers();
        return users;
    }

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        User user = userMapper.getUser(id);
        return user;
    }

    @PostMapping("/user/create")
    public User insertUser(@RequestBody User user) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        user.setCreateDate(timestamp);
        userMapper.insertUser(user);
        return user;
    }

    @PostMapping("/user/update")
    public User updateUser(@RequestBody User user) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        user.setCreateDate(timestamp);
        userMapper.updateUser(user);
        return user;
    }

    @PostMapping("/user/create/batch")
    public List<User> insertUser(@RequestBody List<User> users) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        users.forEach(user -> {
            user.setCreateDate(timestamp);
        });

        userMapper.batchInsertUser(users);
        return users;
    }

    @PostMapping("/user/delete/{id}")
    public List<User> deleteUser(@PathVariable("id") Long id) {
        userMapper.deleteUser(id);
        return getUser();
    }

    @PostMapping("/user/delete/batch")
    public List<User> updateUser(@RequestBody List<Long> ids) {
        userMapper.batchDeleteUser(ids);
        return getUser();
    }

    @GetMapping("/user/all/{page}/{size}")
    public PageInfo<User> getUser(@PathVariable("page") int page, @PathVariable("size") int size) {
        //方法1
        //List<User> users = PageHelper.startPage(page, size).doSelectPage(() -> userMapper.listUsers());
        //return users;

        //方法2
        //PageHelper.startPage(page, size);
        //List<User> users = userMapper.listUsers();
        //Page<User> userPage = (Page<User>) users;
        //return userPage;

        //方法4
        PageHelper.startPage(page, size);
        List<User> users = userMapper.listUsers();
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;

        //return null;
    }

    @GetMapping("/user/all/flip")
    public List<User> getUser2() {
        //方法3
        PageHelper.startPage(request);
        List<User> users = userMapper.listUsers();
        Page<User> userPage = (Page<User>) users;
        return userPage;
    }
}
复制代码

说明:

在获取全部user数据的时候使用了分页插件并实现了四种方法,具体相关文档可以参照 mybatis分页插件官方文档 。

原文  https://juejin.im/post/5c734d39e51d454cd153a47b
正文到此结束
Loading...