如何用请求参数创建一个成功的get api?

fnx2tebb  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(319)

我正在创建一个基本的getapi,它可以获取名字、姓氏、电子邮件和电话的详细信息,也可以是上面提到的任何一个。我在controller类中使用了以下代码。

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能为我获取细节。怎么可能?这个代码不工作,相反,我需要输入所有的参数,它的工作方式。

axkjgtzd

axkjgtzd1#

这个问题已经有答案了!任何一种方法都有一个解决方案。
解决方案-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;
}

REST控制器

@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

相关问题