虚拟主机建网站,太原市手机网站建设,公司 网站制作,做图片可以卖给那些网站你好朋友#xff0c; 在本教程中#xff0c;您将学习以下内容#xff1a; 1.在Spring Boot中配置Spring Rest#xff0c;Spring Data JPA和H2 2.使用Spring Boot创建Springful服务端点的Spring Rest#xff0c;Spring Data JPA和H2的示例 3.使用Swagger测试Restful端点… 你好朋友 在本教程中您将学习以下内容 1.在Spring Boot中配置Spring RestSpring Data JPA和H2 2.使用Spring Boot创建Springful服务端点的Spring RestSpring Data JPA和H2的示例 3.使用Swagger测试Restful端点 1.在Spring Boot中配置Spring RestSpring Data JPA和H2 转到https://start.spring.io/并创建一个名为springRestAndDataJpaWithSpringBoot并具有以下依赖项的项目 –网页 – JPA – H2 注意如果您不熟悉使用Spring Initializer创建Spring Boot项目我建议您参考我以前的文章之一 如何使用Spring Initializer创建Spring Boot项目 我在上面详细解释了如何创建Spring Boot项目。使用Spring Initializer。 2.使用Spring Boot创建Springful服务端点的Spring RestSpring Data JPA和H2的示例 在此示例中我们将创建Rest端点以 –创建员工资源 –检索员工名单 –检索员工 –更新员工资源 –删除员工资源 以下是项目的最终目录结构 让我们看看我们需要创建的各种类和接口。 步骤1 从目录将项目springRestAndDataJpaWithSpringBoot通过Spring Initializer创建的导出到Eclipse。 第2步 打开Pom.xml它应该具有从spring初始化器网站添加的所有依赖项以及一些默认依赖项。 另外我手动添加了依赖项以启用Swagger。 Swagger基本上用于测试其余端点。 ?xml version1.0 encodingUTF-8?project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersion
groupIdnl.blogspot.javasolutionsguide/groupId
artifactIdspringRestAndDataJpaWithSpringBoot/artifactId
version0.0.1-SNAPSHOT/version
packagingjar/packaging
namespringRestAndDataJpaWithSpringBoot/namedescriptionDemo project for Spring Boot/descriptionparent
groupIdorg.springframework.boot/groupId
artifactIdspring-boot-starter-parent/artifactId
version2.0.3.RELEASE/version
relativePath/ !-- lookup parent from repository --
/parentproperties
project.build.sourceEncodingUTF-8/project.build.sourceEncoding
project.reporting.outputEncodingUTF-8/project.reporting.outputEncoding
java.version1.8/java.version
/propertiesdependenciesdependency
groupIdorg.springframework.boot/groupId
artifactIdspring-boot-starter-data-jpa/artifactId
/dependencydependency
groupIdorg.springframework.boot/groupId
artifactIdspring-boot-starter-data-rest/artifactId
/dependencydependency
groupIdcom.h2database/groupId
artifactIdh2/artifactId
scoperuntime/scope
/dependencydependency
groupIdorg.springframework.boot/groupId
artifactIdspring-boot-starter-test/artifactId
scopetest/scope
/dependencydependency
groupIdio.springfox/groupId
artifactIdspringfox-swagger2/artifactId
version2.7.0/version
/dependencydependency
groupIdio.springfox/groupId
artifactIdspringfox-swagger-ui/artifactId
version2.7.0/version
/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin
/plugins/build/project第三步 Spring Boot自动创建了一个名为SpringRestAndDataJpaWithSpringBootApplication的Java文件。 此类用于启动Spring Boot应用程序。 我们需要在这个课上做以下事情 –启用招摇 我们已经在Pom.xml中添加了Swagger的依赖关系。此外为了在Spring Boot中启用Swagger我们需要在 EnableSwagger2注释的顶部放置 SpringRestAndDataJpaWithSpringBootApplication类。 –告诉Spring Boot扫描哪些软件包以考虑由Spring管理的bean 我们需要在SpringRestAndDataJpaWithSpringBootApplication类的顶部使用ComponentScanbasePackages “ nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot”。 第四步 创建员工实体 package nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.entity;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;/*** author JavaSolutionsGuide**/
Entity
Table(nameEMPLOYEE)
public class Employee {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;Column(nameEMPLOYEE_NAME)private String name;Column(nameEMPLOYEE_SALARY)private Integer salary;Column(nameDEPARTMENT)private String department;public Long getId() {return id;}public void setId(Long id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}public Integer getSalary() {return salary;}public void setSalary(Integer salary) {this.salary salary;}public String getDepartment() {return department;}public void setDepartment(String department) {this.department department;}
}第5步 创建具有所有操作的Rest Controller。 package nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.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.RestController;
import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.entity.Employee;
import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.service.EmployeeService;/*** author JavaSolutionsGuide**/
RestController
public class EmployeeRestController {Autowiredprivate EmployeeService employeeService;public void setEmployeeService(EmployeeService employeeService) {this.employeeService employeeService;}GetMapping(/api/employees)public ListEmployee getEmployees() {ListEmployee employees employeeService.retrieveEmployees();return employees;}GetMapping(/api/employees/{employeeId})public Employee getEmployee(PathVariable(nameemployeeId)Long employeeId) {return employeeService.getEmployee(employeeId);}PostMapping(/api/employees)public void saveEmployee(Employee employee){employeeService.saveEmployee(employee);System.out.println(Employee Saved Successfully);}DeleteMapping(/api/employees/{employeeId})public void deleteEmployee(PathVariable(nameemployeeId)Long employeeId){employeeService.deleteEmployee(employeeId);System.out.println(Employee Deleted Successfully);}PutMapping(/api/employees/{employeeId})public void updateEmployee(RequestBody Employee employee,PathVariable(nameemployeeId)Long employeeId){Employee emp employeeService.getEmployee(employeeId);if(emp ! null){employeeService.updateEmployee(employee);}}}第6步 创建Service接口其中包含检索雇员列表一名雇员将雇员保存在数据库中删除雇员以及更新和雇员所需的方法。 package nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.service;import java.util.List;import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.entity.Employee;/*** author JavaSolutionsGuide**/
public interface EmployeeService {public ListEmployee retrieveEmployees();public Employee getEmployee(Long employeeId);public void saveEmployee(Employee employee);public void deleteEmployee(Long employeeId);public void updateEmployee(Employee employee);
}步骤7 为在步骤6中创建的接口创建实现类 package nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.service.impl;import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.entity.Employee;
import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.repository.EmployeeRepository;
import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.service.EmployeeService;/*** author JavaSolutionsGuide**/
Service
public class EmployeeServiceImpl implements EmployeeService{Autowiredprivate EmployeeRepository employeeRepository;public void setEmployeeRepository(EmployeeRepository employeeRepository) {this.employeeRepository employeeRepository;}public ListEmployee retrieveEmployees() {ListEmployee employees employeeRepository.findAll();return employees;}public Employee getEmployee(Long employeeId) {OptionalEmployee optEmp employeeRepository.findById(employeeId);return optEmp.get();}public void saveEmployee(Employee employee){employeeRepository.save(employee);}public void deleteEmployee(Long employeeId){employeeRepository.deleteById(employeeId);}public void updateEmployee(Employee employee) {employeeRepository.save(employee);}
}步骤8 创建一个存储库类它将扩展Spring数据JPA JpaRepository因此将提供开箱即用地执行CRUD操作的方法。 package nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.repository;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import nl.blogspot.javasolutionsguide.springRestAndDataJpaWithSpringBoot.entity.Employee;Repository
public interface EmployeeRepository extends JpaRepositoryEmployee,Long{}步骤9 通过在application.properties文件中添加以下行来启用H2数据库Web控制台 spring.h2.console.enabledtruespring.h2.console.path/h2 Spring Boot将自动处理H2数据库的数据源的创建但是我们也可以在application.properties文件中配置数据源如下所示 spring.datasource.urljdbc:h2:file:~/testspring.datasource.usernamesaspring.datasource.passwordspring.datasource.driver-class-nameorg.h2.Driver第10步 这样您就可以使用Spring Rest和带有h2数据库的spring data JPA创建您的Restful API。 现在您只需要运行SpringRestAndDataJpaWithSpringBootApplication.java类它将确保它将生成您的代码将代码打包在jar中然后将其部署到嵌入式tomcat服务器上。 步骤11 通过点击以下URL打开H2数据库控制台 http://localhost:8080/h2/ 它将显示以下屏幕 单击“连接”按钮它将把您连接到H2数据库。 并且您可以看到EMPLOYEE表已创建但是该表中没有数据这与我们预期的一样。 3.使用Swagger测试Restful端点 要测试您的其余端点请点击以下Swagger URL http://localhost:8080/swagger-ui.html 它将打开以下页面 单击“ employee-rest-controller”链接。 它将向您显示此控制器支持的操作如下所示 现在我们可以在上面的屏幕快照中看到五个端点。 我们将一一测试。 挽救员工– / api / employees 我们要做的第一件事是在数据库中创建资源为此我们将使用POST操作并使用/ api / employees端点。 单击saveEmployee并填写我们创建资源所需的所有必需数据然后单击“试用”按钮。 这就是您的请求和响应的样子 如您所见响应代码为200表示成功因此我们的记录应该已经在H2数据库中创建了。 让我们检查一下。 打开H2 Web控制台并查询EMPLOYEE表您可以看到我们从Swagger UI推送的记录。 同样从Swagger UI中再插入一名雇员并输入以下数据 再次查询数据库您将在数据库中看到两条记录如下所示 获取员工-/ api /员工 现在由于我们已经在数据库中插入了两个记录我们将尝试在GET操作的帮助下并使用/ api / employees端点来检索这些记录如下所示 单击getEmployees然后由于我们要检索所有雇员的列表因此无需传递任何参数。 因此只需单击“尝试一下”按钮您就会在响应中看到一个员工列表。 获取员工 接下来我们将使用GET操作根据输入的employeeId仅检索一名雇员。 我们将把employeeId传递给其余端点/ api / employees / {employeeId}。 单击getEmployee并将employeeId填充为1这意味着我们要检索employeeId为1的雇员。 单击尝试按钮您将在响应中看到具有employeeId 1的雇员的数据如下所示 更新员工-/ api / employees / {employeeId} 接下来我们将使用PUT操作和/ api / employees / {employeeId}端点来测试更新的员工休息端点。 单击updateEmployee链接。 粘贴employee json之一并放入相应的employeeId如下所示 单击“试用”按钮您将看到以下响应响应代码为200SUCCESS。 验证雇员ID为1的员工在H2数据库的EMPLOYEE表中将薪水从1000更新为3000的更新记录。 删除员工– 接下来我们将使用DELETE操作并使用/ api / employees / {employeeId}端点来测试delete Employee rest端点。 单击deteleEmployee链接并填写employeeId 1这意味着我们要删除具有employeeId 1的雇员。 单击“试用”按钮您将获得响应代码200这表示请求已成功处理。 让我们通过打开H2控制台并查询数据库来验证是否已成功从数据库中删除了具有employeeId 1的雇员。 正如我们在上面看到的那样我们在EMPLOYEE表中只有雇员id为2的雇员因此雇员id为1的雇员已被成功删除。 摘要 因此在以上文章中我们看到了如何使用Spring RestSpring Data JPA和带有Spring Boot的H2数据库来创建Restful API。 我们要 –使用必需的依赖项从spring Initializer创建Spring Boot项目。 –通过在POM.xml中添加其他依赖项并在spring boot应用程序类中添加批注来启用swagger支持。 –通过在application.properties中添加必要的属性来启用H2数据库。 –编写要使用的Rest Controller服务存储库和实体。 –启动Spring Boot应用程序它将自动部署到嵌入式服务器。 –使用Swagger UI测试其余端点并使用H2控制台验证H2数据库中的数据。 谢谢阅读。 与您认为有帮助的人分享。 翻译自: https://www.javacodegeeks.com/2018/08/restful-api-spring-rest-data-jpa-h2.html