@[TOC](SpringBoot: RESTful Web APP连接mysql(Spring Data JPA))
0. 系统版本
- 操作系统:window10
- spring boot :2.1.4 release
- eclipse Version : 2019-03 (4.11.0)
- java : Oracle JDK 1.8
- maven : 3.5.4
1. mysql中创建测试数据库
执行以下sql
create database db_example
2. 配置application.properties
默认使用的数据库是H2,因此需要自己配置
修改src/main/resources/application.properties文件,内容如下:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto有四种模式:none(默认),update,create,create-drop
注意第一次运行程序用create来创建table,以后改成none,如果表结构需要修改改成update。
3. 修改POM.xml
- 首先需要继承母POM: spring-boot-starter-parent
- 选用依赖:
- spring-boot-starter-web
- spring-boot-starter-test
- spring-boot-starter-data-jpa
- mysql-connector-java
- spring-boot-devtools
- 构建组件:spring-boot-maven-plugin (打包用)
<?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.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.hiramchen</groupId>
<artifactId>SpringBoot-rest-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot-rest-service</name>
<description>SpringBoot-rest-service</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. 创建@Entity模型User.java
@Entity注解可以让Hibernate根据模型自动生成数据表
package com.hiramchen.hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
5. 创建仓库UserRepository.java
package com.hiramchen.hello;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User,Integer> {
}
6. 创建控制器UserController.java
编写RESTful风格的接口
package com.hiramchen.hello;
import java.util.Optional;
import javax.swing.text.html.Option;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public Iterable<User> getAllUsers(){
return userRepository.findAll();
}
@GetMapping(path="/{id}")
public User getUser(@PathVariable Integer id) {
Optional<User> opt = userRepository.findById(id);
if (opt.isPresent()) {
return opt.get();
}
else {
return new User();
}
}
@PostMapping
public String addNewUser(@RequestBody User user) {
User n = new User();
n.setName(user.getName());
n.setEmail(user.getEmail());
userRepository.save(n);
return "Saved";
}
@PostMapping("/{id}")
public String editUser(@PathVariable Integer id,@RequestBody User user) {
Optional<User> opt = userRepository.findById(id);
if (opt.isPresent()) {
User n = opt.get();
n.setName(user.getName());
n.setEmail(user.getEmail());
userRepository.save(n);
return "Modified";
}
else {
return "Can't find this item!";
}
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Integer id) throws Exception{
try {
userRepository.deleteById(id);
return String.format("Delete item %d success", id);
}
catch(Exception e) {
return "Delete Failed";
}
}
}
7. 测试
自己通过前端(表单、ajax、promise,fetch等)或者一些能发送请求的小工具来测试接口:
- 新增一个User
POST: http://localhost:8080/api/user
注意content-type=application/json - 这时候数据库里自动创建了table,将application.properties中改回spring.jpa.hibernate.ddl-auto=none,不然每次都会重新创建table
- 查询所有User
GET: http://localhost:8080/api/user - 查询一个User
GET: http://localhost:8080/api/user/1 - 修改User
POST: http://localhost:8080/api/user/1 - 删除User
DELETE: http://localhost:8080/api/user/1