第一章 Restful简介

Restful是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服

务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

在服务器端,应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体,它向客户端公开。资源的例子

有:应用程序对象、数据库记录、算法等等。每个资源都使用 URI (Universal Resource Identifier) 得到一个唯一的

地址。所有资源都共享统一的接口,以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、

PUT、POST 和 DELETE。Hypermedia 是应用程序状态的引擎,资源表示通过超链接互联。

在基于Rest的设计中,使用一组通用的动词来操作资源:

要创建资源:应使用HTTP POST

要检索资源:应该使用HTTP GET

要更新资源:应使用HTTP PUT

要删除资源:应该使用HTTP DELETE

第二章 基于 JPA 的 Restful 风格的数据

2.1、构建开发环境

JDK 1.8或更高版本

Maven的3.0+

IntelliJ IDEA集成开发环境

sql脚本:

DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(50) NOT NULL,

`address` varchar(100) NOT NULL,

`photo` varchar(200) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;

/*Data for the table `employee` */

insert into `employee`(`id`,`name`,`address`,`photo`) values

(1001,'张三','北京','a.jpg'),

2.2、pom.xml文件

(1002,'李四','上海','b.jpg');

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">

4.0.0

com.qianfeng.springboot

jpa-restful

0.0.1-SNAPSHOT

jar

springboot2-mybatis-annotation

Demo project for Spring Boot

org.springframework.boot

spring-boot-starter-parent

2.0.3.RELEASE

UTF-8

UTF-8

1.8

org.springframework.boot

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.3.2

mysql

mysql-connector-java

runtime

org.springframework.boot

2.1、配置application.properties属性文件

主要是配置数据库的连接、以及jpa的一些属性

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-data-jpa

com.alibaba

druid-spring-boot-starter

1.1.9

org.springframework.boot

spring-boot-maven-plugin

server:

port: 8080

spring:

datasource:

name: restful

type: com.alibaba.druid.pool.DruidDataSource

#druid相关配置

druid:

#监控统计拦截的filters

filters: stat

driver-class-name: com.mysql.jdbc.Driver

#基本属性

url: jdbc:mysql://127.0.0.1:3306/restful?useUnicode=true&characterEncoding=UTF-

8&allowMultiQueries=true

username: root

password: weizhigang

#配置初始化大小/最小/最大

initial-size: 1

min-idle: 1

max-active: 20

#获取连接等待超时时间

2.3、定义Restful风格访问的URL

2.4、定义JPA 的Repository接口

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

#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多

推荐设置为false

pool-prepared-statements: false

max-pool-prepared-statement-per-connection-size: 20

jpa:

# 配置 DBMS 类型

database: MYSQL

# 配置是否将执行的 SQL 输出到日志

show-sql: true

properties:

hibernate:

hbm2ddl:

# update 只在第一次加载hibernate时自动生成数据库表结构,以后再次加载hibernate时根据model类自

动更新表结构;

auto: update

package com.qianfeng.springboot.constants;

public class EmpRestURIConstants {

public static final String GET_EMP = "/emps";

public static final String CREATE_EMP = "/emp/create";

public static final String DELETE_EMP = "/emp/delete/{id}";

public static final String UPDATE_EMP = "/emp/update/{id}";

public static final String FIND_EMP = "/emp/findone/{id}";

public static final String DELETE_ALL = "/emp/deleteall";

}

2.4、定义JPA的POJO类(包含注解)

package com.qianfeng.springboot.repository;

import com.qianfeng.springboot.model.Employee;

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmpRepository extends JpaRepository {

}

package com.qianfeng.springboot.model;

import javax.persistence.*;

@Entity

@Table(name = "employee")

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

@Column

private String name;

@Column

private String address;

@Column

private String photo;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

2.3、定义Service组件以及实现类

服务接口:

public String getPhoto() {

return photo;

}

public void setPhoto(String photo) {

this.photo = photo;

}

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (!(o instanceof Employee)) return false;

Employee employee = (Employee) o;

if (!id.equals(employee.id)) return false;

if (!name.equals(employee.name)) return false;

if (!address.equals(employee.address)) return false;

return photo.equals(employee.photo);

}

@Override

public int hashCode() {

int result = id.hashCode();

result = 31 * result + name.hashCode();

result = 31 * result + address.hashCode();

result = 31 * result + photo.hashCode();

return result;

}

}

package com.qianfeng.springboot.service;

import com.qianfeng.springboot.model.Employee;

import org.springframework.data.domain.Example;

import java.util.List;

import java.util.Optional;

public interface EmpService {

public List findAllEmps();

public Optional findEmpByID(Integer id);

public void deleteEmp(Integer id);

public void deleteAllEmp();

public void updateEmp(Employee employee);

public void saveEmp(Employee employee);

public boolean existEmp(Example example);

}

实现类:

package com.qianfeng.springboot.service.impl;

import com.qianfeng.springboot.model.Employee;

import com.qianfeng.springboot.repository.EmpRepository;

import com.qianfeng.springboot.service.EmpService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Example;

import org.springframework.stereotype.Service;

import java.util.List;

import java.util.Optional;

@Service

public class EmpServiceImp implements EmpService {

@Autowired

private EmpRepository repository;

@Override

public List findAllEmps() {

return repository.findAll();

}

@Override

public Optional findEmpByID(Integer id) {

Optional employee = repository.findById(id);

return employee;

}

@Override

public void deleteEmp(Integer id) {

repository.deleteById(id);

}

@Override

public void deleteAllEmp() {

repository.deleteAll();

}

@Override

public boolean existEmp(Example example) {

return repository.exists(example);

}

@Override

public void updateEmp(Employee employee) {

repository.saveAndFlush(employee);

}

2.4、定义Controller控制器

package com.qianfeng.springboot.controller;

import com.qianfeng.springboot.constants.EmpRestURIConstants;

import com.qianfeng.springboot.model.Employee;

import com.qianfeng.springboot.service.EmpService;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Example;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

@RestController

@RequestMapping("/api")

public class EmpController {

public static final Logger logger = LoggerFactory.getLogger(EmpController.class);

@Autowired

private EmpService service;

/**

* @param id

* @return

*/

@RequestMapping(value = EmpRestURIConstants.FIND_EMP, method = RequestMethod.GET)

public ResponseEntity> findEmpByID(@PathVariable("id") Integer id) {

logger.info("employee id is " + id);

Employee employee = service.findEmpByID(id).get();

if (employee == null) {

logger.info("employee is not found");

return new ResponseEntity("employee is not found",

HttpStatus.NOT_FOUND);

}

return new ResponseEntity(employee, HttpStatus.OK);

}

/**

* @return

*/

@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)

@Override

public void saveEmp(Employee employee) {

repository.save(employee);

}

}

public ResponseEntity> findAllEmp() {

List list = service.findAllEmps();

if (list.isEmpty()) {

return new ResponseEntity(HttpStatus.NO_CONTENT);

}

return new ResponseEntity>(list, HttpStatus.OK);

}

/**

* @param id

* @return

*/

@RequestMapping(value = EmpRestURIConstants.DELETE_EMP, method = RequestMethod.GET)

public ResponseEntity> deleteEmp(@PathVariable("id") Integer id) {

logger.info("delete employee by id");

Employee employee = service.findEmpByID(id).get();

if (employee == null) {

return new ResponseEntity("unable to delete with id:" + id,

HttpStatus.NOT_FOUND);

}

service.deleteEmp(id);

return new ResponseEntity(HttpStatus.OK);

}

@RequestMapping(value = EmpRestURIConstants.CREATE_EMP, method = RequestMethod.POST)

public ResponseEntity> createEmp(@RequestBody Employee employee, UriComponentsBuilder

builder) {

// logger.info("employee:" + employee);

System.out.println("----->>");

if (service.existEmp(Example.of(employee))) {

logger.info("对象已经存在了");

return new ResponseEntity("name is exist" + employee.getName(),

HttpStatus.CONFLICT);

}

service.saveEmp(employee);

return new ResponseEntity(HttpStatus.OK);

}

@RequestMapping(value = EmpRestURIConstants.UPDATE_EMP, method = RequestMethod.POST)

public ResponseEntity> updateEmp(@PathVariable("id") Integer id, @RequestBody Employee

employee) {

Employee current = service.findEmpByID(id).get();

if (current == null) {

return new ResponseEntity(HttpStatus.NOT_FOUND);

}

current.setAddress(employee.getAddress());

current.setName(employee.getName());

current.setPhoto(employee.getPhoto());

service.saveEmp(current);

return new ResponseEntity(current, HttpStatus.OK);

}

@RequestMapping(value = EmpRestURIConstants.DELETE_ALL, method = RequestMethod.GET)

public ResponseEntity> deleteALlEmp() {

service.deleteAllEmp();

return new ResponseEntity(HttpStatus.OK);

}

}

2.5 测试

启动项目,打开postman工具。

2.5.1 emps

选择GET方式,输入http://localhost:8080/api/emps,查询所有的纪录,见如下效果:

2.5.2 /emp/create

选择POST方式,输入http://localhost:8080/api/emp/create,创建纪录,见如下效果:

{"name": "张三","address": "北京","photo": "c.jpg"}

2.5.3 /emp/delete/{id}

选择GET方式,输入http://localhost:8080/api/emp/delete/1006,删除某条纪录,见如下效果:

2.5.4 /emp/update/{id}

选择POST方式,输入http://localhost:8080/api/emp/update/1001,更新某条纪录。

{"name": "王五","address": "天津","photo": "c.jpg"}

见如下效果:

2.5.5 /emp/findone/{id}

选择GET方式,输入http://localhost:8080/api/emp/findone/1001,查询某条纪录,见如下效果:

2.5.6 /emp/deleteall

选择GET方式,输入http://localhost:8080/api/emp/deleteall,删除所有纪录,见如下效果:

springboot 集成jpa_基于Spring Boot+JPA Restful 风格的数据相关推荐

  1. boot spring 接口接收数据_基于 Spring Boot 实现 Restful 风格接口,实现增删改查功能...

    优质文章,及时送达 Spring Boot介绍 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配 ...

  2. 基于 Spring Boot 的 Restful 风格实现增删改查

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  3. JPA的单向一对多关联(oneToMany)实现示例(基于Spring Boot + JPA +MySQL,表自动维护)

    本篇的环境 本篇基于Spring Boot + JPA+ MySQL. 表自动维护: 配置 ddl-auto: update,使用 Hibernate 根据类自动维护表. 本篇的示例 这里有两个类: ...

  4. springboot毕设项目基于Spring Boot的智慧天气管理系统84z99(java+VUE+Mybatis+Maven+Mysql)

    springboot毕设项目基于Spring Boot的智慧天气管理系统84z99(java+VUE+Mybatis+Maven+Mysql) 项目运行 环境配置: Jdk1.8 + Tomcat8. ...

  5. 用Kotlin写一个基于Spring Boot的RESTful服务

    Spring太复杂了,配置这个东西简直就是浪费生命.尤其在没有什么并发压力,随便搞一个RESTful服务 让整个业务跑起来先的情况下,更是么有必要纠结在一堆的XML配置上.显然这么想的人是很多的,于是 ...

  6. Spring boot的Restful风格CRUD

    Restful风格 RestfulCRUD 表示,CRUD满足Rest风格 URI:/资源名称/资源标识 HTTP请求方式,区分对资源CRUD操作 Emp,资源名称 增删改查 请求方式

  7. spring boot+jpa+MySQL格式化返回数据中实体对象对应的日期格式

    在controller中设置返回参数中的日期格式有三种: 1.在配置文件application.yml中设置整个项目关于日期的格式: spring: jackson: time-zone: GMT+8 ...

  8. SOFABoot是蚂蚁金服开源的基于Spring Boot的研发框架

    前言 SOFABoot是蚂蚁金服开源的基于Spring Boot的研发框架,它在Spring Boot的基础上,提供了诸如 Readiness Check,类隔离,日志空间隔离等等能力.在增强了 Sp ...

  9. java restful接口开发实例_实战:基于Spring Boot快速开发RESTful风格API接口

    写在前面的话 这篇文章计划是在过年期间完成的,示例代码都写好了,结果亲戚来我家做客,文章没来得及写.已经很久没有更新文章了,小伙伴们,有没有想我啊.言归正传,下面开始,今天的话题. 目标 写一套符合规 ...

最新文章

  1. 配置思路ensp_配置OSPF的Stub区域示例
  2. Tinyhttpd的实现和一些基本问题的解决
  3. 分布式队列编程:模型、实战
  4. java restsharp_C# RestSharp应用
  5. IDEA调试技巧之条件断点
  6. Spring4 SpringMVC Hibernate4 Freemaker 集成示例
  7. java通过InputStream读取文件
  8. C# 利用SQLite对.DB和.logdb加密和解密和SQLite创建数据库
  9. [导入].net中设置系统时间
  10. 通过shell和redis来实现集群业务中日志的实时收集分析
  11. 同是4G标准,TD和FDD怎么区分?谁更快?
  12. 盘点服装进销存软件和生产进销存软件排行榜
  13. V831基础-摄像头使用
  14. 2018ICPC焦作站赛后总结
  15. enscape3.1完美中文版
  16. Linux 面试知识点
  17. 最新研究报告: 坐飞机哪个位置最安全?
  18. 普通相片打印纸如何长时间保存
  19. Windows+Visual stdio+CUDA编程方式及测试
  20. 智能机器人-(一)常用传感器及其原理

热门文章

  1. Git 高级用法,喜欢就拿去用!
  2. 太赞了:中文版开源!这或许是最经典的计算机编程教材
  3. 用数据告诉你王思聪到底有多少钱?
  4. 这么多年来,我算想明白了!
  5. locust压测工具:测试信息输出与分布式模式
  6. m个足球放入n个篮子中或者放苹果问题
  7. 美多后台管理和项目环境搭建
  8. MySQL数据库使用连接更新表中某个字段数据
  9. JSP网页开发安装2019-03 eclipse,详细并且简单教程这里有。
  10. C语言找最大的int型数!_只愿与一人十指紧扣_新浪博客