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

栏目: Java · 发布时间: 5年前

内容简介:说明:写了通用的增删改查以及部分批量操作。具体请看mybatis官方文档。
  • 操作系统: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分页插件官方文档


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

奈飞文化手册

奈飞文化手册

[美] 帕蒂·麦考德 / 范珂 / 浙江教育出版社 / 2018-10-1 / 69

一本对奈飞文化进行深入解读的力作。2009年,奈飞公开发布了一份介绍企业文化的PPT文件,在网上累计下载量超过1500万次,被Facebook的CFO谢丽尔·桑德伯格称为“硅谷重要文件”。本书是奈飞前CHO,PPT的主要创作者之一帕蒂·麦考德对这份PPT文件的深度解读。 本书系统介绍奈飞文化准则,全面颠覆20世纪的管人理念。在这本书中,帕蒂·麦考德归纳出8条奈飞文化准则,从多个角度揭示了奈飞......一起来看看 《奈飞文化手册》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具