Spring Boot Jpa 简明教程

Spring Boot JPA - Application Setup

与上一章 Environment Setup 中一样,我们已在 Eclipse 中导入了已生成的 Spring Boot 项目。现在,让我们在 src/main/java 文件夹中创建以下结构。

project structure
  1. com.tutorialspoint.controller.EmployeeController ——一个REST基于控制器实现REST基于API。

  2. com.tutorialspoint.entity.Employee ——一个实体类表示数据库中对应的表。

  3. com.tutorialspoint.repository.EmployeeRepository ——一个存储库接口来执行crud操作库。

  4. com.tutorialspoint.service.EmployeeService ——一个服务类来执行业务操作库函数。

  5. com.tutorialspoint.springbooth2.SprintBootH2Application ——一个SpringBoot应用程序类。

SprintBootH2Application类已存在。我们须创建上述包和相关类和接口如下所示——

Entity - Entity.java

以下为Employee的默认代码。它表示一个带id,name,age和email列的Employee表。

package com.tutorialspoint.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Employee {
   @Id
   @Column
   private int id;

   @Column
   private String name;

   @Column
   private int age;

   @Column
   private String email;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getEmail() {
      return email;
   }
   public void setEmail(String email) {
      this.email = email;
   }
}

Repository - EmployeeRepository.java

以下为实现上述实体创建CRUD操作的存储库的默认代码,Employee。

package com.tutorialspoint.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.tutorialspoint.entity.Employee;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>  {
}

Service - EmployeeService.java

以下为实现库函数操作的服务的默认代码。

package com.tutorialspoint.service;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;

@Service
public class EmployeeService {
   @Autowired
   EmployeeRepository repository;

   public Employee getEmployeeById(int id) {
      return repository.findById(id).get();
   }
   public List<Employee> getAllEmployees(){
      List<Employee> employees = new ArrayList<Employee>();
      repository.findAll().forEach(employee -> employees.add(employee));
      return employees;
   }
   public void saveOrUpdate(Employee employee) {
      repository.save(employee);
   }
   public void deleteEmployeeById(int id) {
      repository.deleteById(id);
   }
}

Controller - EmployeeController.java

以下为实现REST API的控制器的默认代码。

package com.tutorialspoint.controller;

import java.util.List;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;

@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;

   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return employeeService.getAllEmployees();
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return employeeService.getEmployeeById(id);
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
      employeeService.deleteEmployeeById(id);
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
}

Application - SprintBootH2Application.java

以下为用于使用上述类的Application的更新代码。

package com.tutorialspoint.sprintbooth2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan({"com.tutorialspoint.controller","com.tutorialspoint.service"})
@EntityScan("com.tutorialspoint.entity")
@EnableJpaRepositories("com.tutorialspoint.repository")
@SpringBootApplication
public class SprintBootH2Application {
   public static void main(String[] args) {
      SpringApplication.run(SprintBootH2Application.class, args);
   }
}

Run/Debug Configuration

在eclipse中创建以下 maven configuration 来运行带目标 spring-boot:run 的springboot应用程序。此配置将有助于运行REST API,我们可以使用POSTMAN对其进行测试。

maven configuration

Run the application

在 Eclipse 中,运行 Employee Application 配置。Eclipse 控制台将显示类似的输出。

[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823  INFO 9760 --- [restartedMain] c.t.s.SprintBootH2Application:
Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,使用 Postman 先执行 POST 请求以添加记录。

在 POSTMAN 中设置以下参数。

  1. HTTP Method - POST

  2. URL - http://localhost:8080/emp/employee

  3. 正文 - An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

单击发送按钮并检查响应状态是否为 OK。现在执行 GET 请求以获取所有记录。

在 POSTMAN 中设置以下参数。

  1. HTTP Method - GET

  2. URL - http://localhost:8080/emp/employees

单击发送按钮并验证响应。

[{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}]