如何使用请求参数创建成功的 GET API?
Posted
技术标签:
【中文标题】如何使用请求参数创建成功的 GET API?【英文标题】:How to create a successful GET API with request parameters? 【发布时间】:2021-04-13 21:22:25 【问题描述】:我正在创建一个基本的 GET API,它可以使用 firstName、surName、email 和电话获取详细信息,或者它可以是提到的任何一个。我在控制器类中使用了以下代码。
package com.example.employee.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.employee.entity.Employee;
import com.example.employee.repo.EmployeeRepo;
import com.example.employee.service.EmployeeService;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@RestController
public class EmployeeController
@Autowired
private EmployeeService employeeService;
@RequestMapping(value = "/employees",method = RequestMethod.GET)
public List<Employee> getEmployees()
return employeeService.getEmployees();
@RequestMapping(value = "/employees", method = RequestMethod.POST)
public Employee createEmployee(@RequestBody Employee employee)
return employeeService.createEmployee(employee);
@RequestMapping(value = "/employees/Employee_Id")
public Optional<Employee> getEmployeeById(@PathVariable("Employee_Id") Integer employeeId)
return employeeService.getEmployeeById(employeeId);
@RequestMapping(value = "/employees", method = RequestMethod.PUT)
public Employee updateEmployee(@RequestBody Employee incomingEmployee)
return employeeService.updateEmployee(incomingEmployee);
@RequestMapping(value = "/employees/employeeId", method = RequestMethod.DELETE)
public String deleteEmployeeById(@PathVariable Integer employeeId)
return employeeService.deleteById(employeeId);
@RequestMapping(value= "/employees", method=RequestMethod.GET)
public List<Employee>getEmployeeByParameter(@RequestParam(value="FirstName", required = false)String firstName,
@RequestParam(value="LastName", required = false)String lastName,
@RequestParam(value="Email", required = false)String email,
@RequestParam(value="Phone", required = false)String phone)
return employeeService.findAllByFirstNameAndLastNameAndEmailAndPhone(firstName ,lastName, email,phone);
我在服务类中包含以下内容:
package com.example.employee.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.employee.entity.Employee;
import com.example.employee.repo.EmployeeRepo;
@Service
public class EmployeeService
@Autowired
private EmployeeRepo employeeRepo;
public List<Employee> getEmployees()
List<Employee> employeeList = new ArrayList<>();
employeeRepo.findAll().forEach(employee -> employeeList.add(employee));
return employeeList;
public Employee createEmployee(Employee employee)
return employeeRepo.save(employee);
public Optional<Employee> getEmployeeById(Integer employeeId)
return employeeRepo.findById(employeeId);
public Employee updateEmployee(Employee incomingEmployee)
return employeeRepo.save(incomingEmployee);
public String deleteById(Integer employeeId)
employeeRepo.deleteById(employeeId);
return "Deleted Successfully";
public List<Employee> getUserByEmail(String email)
return employeeRepo.findAllByEmail(email);
public List<Employee> findAllByFirstNameAndLastNameAndEmailAndPhone(String firstName, String lastName, String email,
String phone)
if (firstName != null) return employeeRepo.findAllByFirstName(firstName);
if (lastName != null) return employeeRepo.findAllByLastName(lastName);
if (email != null) return employeeRepo.getUserByEmail(email);
if (phone != null) return employeeRepo.findAllByPhone(phone);
return null;
我在 Repository 类中包含以下内容:
package com.example.employee.repo;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.employee.entity.Employee;
@Repository
public interface EmployeeRepo extends CrudRepository<Employee, Integer>
/*List<Employee> findAllByFirstNameOrLastNameOrEmailOrPhone(String firstName, String lastName, String email,
String phone);*/
@Query(value = "select * from user where firstName=?", nativeQuery = true)
List<Employee> findAllByFirstName(String firstName);
@Query(value = "select * from user where lastName=?", nativeQuery = true)
List<Employee> findAllByLastName(String lastName);
@Query(value = "select * from user where email=?", nativeQuery = true)
List<Employee> findAllByEmail(String email);
@Query(value = "select * from user where phone=?", nativeQuery = true)
List<Employee> findAllByPhone(String phone);
List<Employee> getUserByEmail(String email);
我的 POJO 类:
package com.example.employee.entity;
import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Size;
@Entity
public class Employee
public Employee(int employee_Id, String first_Name, String last_Name, String email, String phone)
super();
employeeId = employee_Id;
firstName = first_Name;
lastName = last_Name;
email = email;
phone = phone;
public Employee()
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int employeeId;
@Size(min = 3, max = 20, message = "Your name should be between 3 - 20 characters.")
private String firstName;
@Size(min = 3, max = 20, message = "Your name should be between 3 - 20 characters.")
private String lastName;
private String email;
private String phone;
public int getEmployee_Id()
return employeeId;
public void setEmployee_Id(int employee_Id)
employeeId = employee_Id;
public String getFirst_Name()
return firstName;
public void setFirst_Name(String first_Name)
firstName = first_Name;
public String getLast_Name()
return lastName;
public void setLast_Name(String last_Name)
lastName = last_Name;
public String getEmail()
return email;
public void setEmail(String email)
this.email = email;
public String getPhone()
return phone;
public void setPhone(String phone)
this.phone = phone;
My application class:
package com.example.employee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmployeeApplication
public static void main(String[] args)
SpringApplication.run(EmployeeApplication.class, args);
我的 SQL 文件:
DROP TABLE IF EXISTS Employee;
CREATE TABLE Employee (
Employee_Id INT AUTO_INCREMENT,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20) NOT NULL,
Email VARCHAR(50),
Phone VARCHAR(20) NOT NULL,
PRIMARY KEY (Employee_Id)
);
INSERT INTO employee (First_Name, Last_Name, Email, Phone)
VALUES ('John','Doe','john.doe@tcs.com','9840098400');
我的属性文件:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username= sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
当我点击请求时,我必须提及所有参数才能使其工作。我希望它的设计方式即使我只提到名字,我也希望 API 为我获取详细信息。这怎么可能?这段代码不能这样工作,我需要输入所有参数才能工作。
【问题讨论】:
您不应该在存储库方法中使用Or
而不是And
来实现您的需要吗? List<User> findAllByFirstNameOrSurNameOrEmailOrPhone(firstName, surName, email, phone)
您所说的“此代码不能那样工作”是什么意思?究竟会发生什么?
你可能想看看 Querydsl。
【参考方案1】:
这个问题已经有了答案!无论如何,这里都有一种解决方案。
解决方案 - 1 [请不要忘记全局处理异常、代码优化、单元测试和 API 测试]
修改您的存储库
@Query(value = "select * from user where firstName=?", nativeQuery = true)
List<User> findAllByFirstName(String firstName);
@Query(value = "select * from user where surName=?", nativeQuery = true)
List<User> findAllBySurName(String surName);
@Query(value = "select * from user where email=?", nativeQuery = true)
List<User> findAllByEmail(String email);
@Query(value = "select * from user where phone=?", nativeQuery = true)
List<User> findAllByPhone(String phone);
服务
public List<User> findAllByFirstNameAndSurNameAndEmailAndPhone(String phone,String email,String firstName,String surName)
if (firstName != null) return userRepository.findAllByFirstName(firstName);
if (surName != null) return userRepository.findAllBySurName(surName);
if (email != null) return userRepository.getUserByEmail(email);
if (phone != null) return userRepository.findAllByPhone(phone);
return null;
休息控制器
@RequestParam(value="FirstName", required = false)String firstName,
@RequestParam(value="SurName", required = false)String surName,
@RequestParam(value="Email", required = false)String email,
@RequestParam(value="Phone", required = false)String phone)
//TODO
return userService.findAllByFirstNameAndSurNameAndEmailAndPhone(String phone,String email,String firstName,String surName);
sir, I hope this will help you
【讨论】:
以上是关于如何使用请求参数创建成功的 GET API?的主要内容,如果未能解决你的问题,请参考以下文章