简体   繁体   English

使用多个搜索参数实现搜索功能

[英]Implementing a Search feature using multiple Search parameters

I am new to learning spring boot, and I am trying this side project where you can search for an employee using 2 parameters, access_pin and org_name.我是学习 spring 引导的新手,我正在尝试这个侧面项目,您可以在其中使用 2 个参数(access_pin 和 org_name)搜索员工。

Let's suppose the employee I wanna search in the database has the following credentials:假设我想在数据库中搜索的员工具有以下凭据:

  • access_pin: 1234访问引脚:1234
  • org_name: PSG组织名称:PSG

My API should retrieve the employee record who has the above match.我的 API 应该检索具有上述匹配项的员工记录。

My REST API URL looks like this:我的 REST API URL 看起来像这样:

http://localhost:8080/employeeSearch/version1/1234/PSG

When I send in the GET request on PostMan, I get a 500 Error.当我在 PostMan 上发送 GET 请求时,我收到 500 错误。

PostMan Screenshot PostMan 截图

This is the Database Table:这是数据库表:

Database table Screenshot数据库表截图

Can I know how does spring handle multiple search parameters and return accurate result from the database?我可以知道 spring 如何处理多个搜索参数并从数据库返回准确的结果吗?

MY backend code looks like this:我的后端代码如下所示:

Model: (Employee.java) Model: (Employee.java)

package com.example.demo.model;

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

@Entity
@Table(name = "employeedatabase")
public class Employee {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long employeeId; 
    
    @Column(name = "employee_name")
    private String employeeName;
    
    @Column(name = "access_pin")
    private long accessPin; 
    
    @Column(name = "org_name")
    private String orgName;
    
    public Employee() {
        
    }

    public Employee(String employeeName, String orgName) {
        super();
        this.employeeName = employeeName;
        this.orgName = orgName;
    }

    public long getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(long employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public long getAccessPin() {
        return accessPin;
    }

    public void setAccessPin(long accessPin) {
        this.accessPin = accessPin;
    }

    public String getOrgName() {
        return orgName;
    }

    public void setOrgName(String orgName) {
        this.orgName = orgName;
    } 
    
    
    
    
    
    
}



Controller: (EmployeeController.java) Controller: (EmployeeController.java)

package com.example.demo.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;



@RestController
@RequestMapping("/employeeSearch/version1")
public class EmployeeController {
    
    @Autowired
    private EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        super();
        this.employeeService = employeeService;
    }
    
    @GetMapping("{accessPin}/{orgName}")
    public ResponseEntity<Employee> getEmployeeNAme(@PathVariable("accessPin") long accessPin, @PathVariable("orgName") String orgName) {
        Employee result = employeeService.getEmployeeName(accessPin, orgName);
        
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }
    
    
}

Service: (EmployeeService.java)服务: (EmployeeService.java)

package com.example.demo.service;

import com.example.demo.model.Employee;

public interface EmployeeService {
    
    Employee getEmployeeName(long accessPin, String orgName) ; 
}

ServiceImpl: (EmployeeServiceImpl.java) ServiceImpl: (EmployeeServiceImpl.java)

package com.example.demo.serviceImpl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;
import com.example.demo.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService{
    
    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public Employee getEmployeeName(long accessPin, String orgName) {
        // TODO Auto-generated method stub
//      return null;
        
        Optional<Employee> employeeName = employeeRepository.findById(accessPin);
        
        
        if(employeeName.get().getAccessPin() == accessPin) {
            return employeeName.get(); 
        }
        else {
            throw new ResourceNotFoundException("The employee does not exist. "); 
        }
    }

}

Repository: (EmployeeRepository.java)存储库: (EmployeeRepository.java)

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.model.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
    

}

Based on your entity the field employee_id is your id.根据您的实体,字段employee_id 是您的ID。 When using the findbyId you are searching using the entity's id.使用 findbyId 时,您正在使用实体的 id 进行搜索。 Hence when you call the function with '1234' you are getting an empty optional and hitting a null pointer exception when Optional::get is called causing the 500 error.因此,当您使用“1234”调用 function 时,您将得到一个空的可选项并在调用 Optional::get 时遇到 null 指针异常,从而导致 500 错误。 For your use case, you can add a custom function to EmployeeRepository as shown below对于您的用例,您可以将自定义 function 添加到 EmployeeRepository,如下所示

Optional<Employee> findByAccessPinAndOrgName(long accessPin, String orgName);

Also when using an Optional value, do check if the value is present before accessing it.此外,当使用可选值时,请在访问之前检查该值是否存在。

Do refer to the articles below for more help on both subjects:请参阅以下文章以获取有关这两个主题的更多帮助:

https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query-methods.query-creation https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query-methods.query-creation

https://www.baeldung.com/java-optional https://www.baeldung.com/java-optional

I see three issues in your code.我在您的代码中看到三个问题。

In your service, you are calling findById but you are passing the accessPin, not the employee ID - employeeRepository.findById(accessPin) .在您的服务中,您正在调用 findById 但您传递的是 accessPin,而不是员工 ID - employeeRepository.findById(accessPin) You should add a findByAccessPin function definition to your repository interface.您应该将findByAccessPin function 定义添加到您的存储库接口。

When dealing with the Optional repository result in your service class, you should call isPresent() on the result before you try to access it with .get() .在您的服务 class 中处理Optional存储库结果时,您应该在尝试使用.get()访问结果之前调用isPresent() ) 。 Calling get on an empty Optional will result in an exception being thrown.对空的 Optional 调用 get 将导致抛出异常。

Finally, your EmployeeController constructor is calling super() but the class has no super class.最后,您的EmployeeController构造函数正在调用 super(),但 class 没有超级 class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM