springboot+mybatis集成restful风格demo

前言:

  1. 开发工具 :IDEA
  2. 版本:2018.03.04
  3. JDK 1.8

搭建springboot项目
4. 构建步骤
file->New->Project->Spring initializr ,点击next在这里插入图片描述

点击next。然后选择项目所需依赖,由于我们需要集成mybatis.需要勾选的依赖如图:
在这里插入图片描述
至此:框架搭建完成。我们需要做的是,建表,构建实体,mapper文件以及service,controller部分。
我贴出pom.xml代码如下所示:

<?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 https://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.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>restfuls</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>restfuls</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-jdbc</artifactId>
        </dependency>
        <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.1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.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-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

个人喜欢使用yml风格,所以将系统给生成的application.propertities文件改成yml文件。
在resources目录下,建立三个yml文件,分别是:
application-dev.yml 开发环境配置文件,
application-prod.yml 生产环境配置文件,
application-uat.yml 测试环境配置文件。
作用也就是用于不同的环境,避免大幅度改动。
对于application.yml文件 我们只需要配置一句话:

spring:
  profiles:
    active: uat

在这里我以测试环境为例,配置文件为application-uat.yml:

server:
  port: 8090


spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_redis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: root
    password: root




mybatis:
  # model的包
  type-aliases-package: com.example.restfuls.domain
  mapper-locations: classpath:mapper/*.xml


里面大致配了一下,数据库连接信息,以及mybatis扫描路径信息。

建立需要的目录结构

在这里插入图片描述
至此:启动springboot启动类,不报错的情况下,代表项目搭建完成。

集成restful风格

package com.example.restfuls.controller;

import com.example.restfuls.ext.UserExt;
import com.example.restfuls.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/users")
public class UserController {


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

    @Autowired
    private UserService userService ;


    /**
     *  @param(参数) :
     *  @Desc(描述) :
     *  ------------------------------
     *
     *  restful风格-查询全部
     *
     *  ------------------------------
     *  @date(日期) : 2019/11/14
     *  @return(返回值) :
     */

    @RequestMapping(value = "" ,method = RequestMethod.GET)
    @ResponseBody
    public List<UserExt> getUsers(){
        List<UserExt> userList = null;
        try {
            userList = userService.getUsers();
            logger.info("返回结果集:"+ userList);
        } catch (Exception e) {
            userList = new ArrayList<>();
            logger.info("查询所有用户异常:方法入口:getUsers",e);
        }
        return userList ;
    }



    /**
     *  @param(参数) :
     *  @Desc(描述) :
     *  ------------------------------
     *
     *  restful风格-根据ID查询用户
     *
     *  ------------------------------
     *  @date(日期) : 2019/11/14
     *  @return(返回值) :
     */

    @RequestMapping(value = "/{id}" ,method = RequestMethod.GET)
    @ResponseBody
    public UserExt getUserByUserId(@PathVariable String id){
        UserExt user = null;
        try {
            user = userService.getUserByUserId(id);
            logger.info("输入用户ID为:"+ id +"|| 返回结果:" + user);
        } catch (Exception e) {
            user = new UserExt();
            logger.info("restful风格-根据ID查询用户:方法入口:getUserByUserId",e);
        }
        return user ;
    }



    /**
     *  @Desc(描述) :
     *  ------------------------------
     *
     *    restful风格-新增用户
     *
     *  ------------------------------
     *  @date(日期) : 2019/11/14
     *  @return(返回值) :
     */

    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public Integer saveUser(@RequestBody UserExt ext){
        int index = 0 ;
        try {
            index = userService.insertUser(ext);
            logger.info("新增成功,index值为:" + index);
        } catch (Exception e) {
            logger.info("新增异常,异常原因为:" ,e);
        }
        return index ;
    }



    /**
     *  @Desc(描述) :
     *  ------------------------------
     *  restful风格-编辑用户-全部更新
     *  ------------------------------
     *  @date(日期) : 2019/11/15
     *  @return(返回值) :
     */

    @RequestMapping(value = "",method = RequestMethod.PUT)
    @ResponseBody
    public Integer putUser(@RequestBody UserExt ext){
        int index = 0 ;
        try {
            index = userService.putUser(ext);
            logger.info("编辑成功,index值为:" + index);
        } catch (Exception e) {
            logger.info("编辑异常,异常原因为:" ,e);
        }
        return index ;
    }




    /**
     *  @Desc(描述) :
     *  ------------------------------
     *  restful风格-编辑用户-局部更新
     *  ------------------------------
     *  @date(日期) : 2019/11/15
     *  @return(返回值) :
     */

    @RequestMapping(value = "",method = RequestMethod.PATCH)
    @ResponseBody
    public Integer patchUser(@RequestBody UserExt ext){
        int index = 0 ;
        try {
            index = userService.patchUser(ext);
            logger.info("编辑成功,index值为:" + index);
        } catch (Exception e) {
            logger.info("编辑异常,异常原因为:" ,e);
        }
        return index ;
    }

    /**
     *  @param(参数) :
     *  @Desc(描述) :
     *  ------------------------------
     *    restful风格-删除用户
     *  ------------------------------
     *  @date(日期) : 2019/11/15
     *  @return(返回值) :
     */

    @RequestMapping(value = "",method = RequestMethod.DELETE)
    @ResponseBody
    public Integer deleteUser(@RequestBody UserExt ext){
        int index = 0 ;
        try {
            index = userService.deleteUser(ext);
            logger.info("删除成功,index值为:" + index);
        } catch (Exception e) {
            logger.info("删除异常,异常原因为:" ,e);
        }
        return index ;
    }
}

这这里,我集成了一般的增删改查
restful风格-查询全部
@RequestMapping(value = “/users” ,method = RequestMethod.GET)
restful风格-根据ID查询用户
@RequestMapping(value = “/users/{id}” ,method = RequestMethod.GET)
restful风格-新增用户
@RequestMapping(value = “/users”,method = RequestMethod.POST)
restful风格-编辑用户-全部更新
@RequestMapping(value = “/users”,method = RequestMethod.PUT)
restful风格-编辑用户-局部更新
@RequestMapping(value = “/users”,method = RequestMethod.PATCH)
restful风格-删除用户
@RequestMapping(value = “/users”,method =RequestMethod.DELETE)

那么什么是restful呢?

REST 指的是一组架构(约束条件)和原则。满足这些(约束条件)和(原则)的应用程序或设计就是 RESTful

restful有什么特点呢?

1.每一个URI代表一种资源,独一无二
2.客户端和服务器之间,传递这种资源的某种表现层
3.客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层状态转化"。

我总结了:

RESTful风格要求每个资源都使用 URI (Universal Resource Identifier) 得到一个唯一的地址。所有资源都共享统一的接口,以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、PUT、POST 和 DELETE。
总之就是REST是一种写法上规范,获取数据或者资源就用GET,更新数据就用PUT,删除数据就用DELETE,然后规定方法必须要传入哪些参数,每个资源都有一个地址。

其实很容易理解。至此全文结束,贴上其他层的代码:
实体:

package com.example.restfuls.domain;


import javax.persistence.Column;
import javax.persistence.Table;

@Table(name = "t_user")
public class UserEntity {
    @Column(name = "id")
    private String id ;

    @Column(name = "user_name")
    private String userName ;

    @Column(name = "password")
    private String password;

    @Column(name = "address")
    private String address;

    public UserEntity() {
    }

    public UserEntity(String id, String userName, String password, String address) {
        this.id = id;
        this.userName = userName;
        this.password = password;
        this.address = address;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "UserEntity{" +
                "id='" + id + '\'' +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

mapper接口:

package com.example.restfuls.mapper;


import com.example.restfuls.ext.UserExt;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface UserMapper {

    List<UserExt> getUsers();

    UserExt getUserByUserId(@Param("userId") String userId);

    void insertUser(UserExt ext);

    void updateUser(UserExt ext);

    int deleteUser(UserExt ext);
}

mapper.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.example.restfuls.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.example.restfuls.ext.UserExt" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
  </resultMap>

    <select id="getUsers" resultMap="BaseResultMap">
		SELECT id,
          user_name,
          password,
          address
		FROM
		  t_user
  </select>



    <select id="getUserByUserId" resultMap="BaseResultMap">
		SELECT id,
          user_name,
          password,
          address
		FROM
		  t_user

		  WHERE id = #{userId}
  </select>


    <insert id="insertUser" parameterType="com.example.restfuls.ext.UserExt">
		 INSERT INTO t_user ( id, user_name, PASSWORD, address )
            VALUES
	    (#{id},#{userName},#{password},#{address});
  </insert>


    <update id="updateUser" parameterType="com.example.restfuls.ext.UserExt">
      UPDATE  t_user
        <trim prefix="set" suffixOverrides=",">
            <if test="userName!=null and userName !=''">user_name=#{userName}</if>
            <if test="password!=null and password !='' ">PASSWORD=#{password}</if>
            <if test="address!=null and address !=''">address=#{address}</if>
        </trim>
      WHERE id = #{id}
  </update>


    <delete id="deleteUser" parameterType="com.example.restfuls.ext.UserExt">
      DELETE FROM t_user WHERE id = #{id}
  </delete>
</mapper>

service接口:

package com.example.restfuls.service;

import com.example.restfuls.ext.UserExt;

import java.util.List;

public interface UserService {

    List<UserExt> getUsers();

    UserExt getUserByUserId(String userId);

    int insertUser(UserExt ext);

    int putUser(UserExt ext);

    int patchUser(UserExt ext);

    int deleteUser(UserExt ext);
}

service实现类:

package com.example.restfuls.service.impl;

import com.example.restfuls.ext.UserExt;
import com.example.restfuls.mapper.UserMapper;
import com.example.restfuls.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public List<UserExt> getUsers() {
        return userMapper.getUsers();
    }

    @Override
    public UserExt getUserByUserId(String userId) {
        return userMapper.getUserByUserId(userId);
    }

    @Override
    public int insertUser(UserExt ext) {
        int index = 0;
        try {
            userMapper.insertUser(ext);
            index = 1;   //成功
        } catch (Exception e) {
            index = -1;   //异常
        }
        return index;
    }

    @Override
    public int putUser(UserExt ext) {
        int index = 0;
        try {
            userMapper.updateUser(ext);
            index = 1;
        } catch (Exception e) {
            index = -1;
        }
        return index;
    }

    @Override
    public int patchUser(UserExt ext) {
        int index = 0;
        try {
            userMapper.updateUser(ext);
            index = 1;
        } catch (Exception e) {
            index = -1;
        }
        return index;
    }

    @Override
    public int deleteUser(UserExt ext) {
        return userMapper.deleteUser(ext);
    }
}

谢谢大家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值