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分页插件官方文档


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

查看所有标签

猜你喜欢:

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

搜索引擎

搜索引擎

李晓明 / 科学出版社发行部 / 2005-4 / 33.00元

《搜索引擎:原理技术与系统》系统地介绍了互联网搜索引擎的工作原理、实现技术及其系统构建方案。《搜索引擎:原理技术与系统》分三篇共13章内容,从基本工作原理概述,到一个小型简单搜索引擎具体细节的实现,进而详细讨论了大规模分布式搜索引擎系统的设计要点及其关键技术;最后介绍了面向主题和个性化的web信息服务,阐述了中文网页自动分类等技术及其应用。《搜索引擎:原理技术与系统》层次分明,由浅入深;既有深入的......一起来看看 《搜索引擎》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器