如何在Spring Controller中使用ID(主键)搜索?

时间:2019-06-25 10:00:50

标签: spring-boot

我正在尝试从JpaRepository的getOne中通过主键来搜索主键

我有一个模型(客户),在其中定义了客户的详细信息。我有一个接口服务(CustomerService)及其实现(实现CustomerService的CustomerServiceImpl)。我还有一个接口存储库(扩展JpaRepository的CustomerRepository。现在在我的控制器中,我将一个ID传递给一个函数(findCustomerById),并使用JpaRepository的getOne

从客户存储库中获取具有该ID的客户。
  

Customer customer = customerRepository.getOne(id);

我一直遇到错误500 (java.lang.NullPointerException: null。我的代码似乎还可以。可能是什么问题? Customer.java

package com.javadevjournal.customer;

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="customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="address")
    private String address;

    public Customer() {
        super();

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

CustomerRepository.java:

package com.javadevjournal.customer;

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

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long>{

}

CustomerController.java:

package com.javadevjournal.customer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import com.javadevjournal.customer.CustomerService;

import javax.validation.Valid;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@RestController
public class CustomerController {

    @Autowired
    private CustomerService  customerService;
    private CustomerRepository customerRepository;

    @GetMapping(path = "/customers")
    public Iterable<Customer> findAll() {
        Iterable<Customer> customers = customerService.findAll();
        return customers;
    }

    // Get a Single Customer
    @GetMapping(path = "/getCustomer/{id}")
    public Customer findCustomerById(@PathVariable("id") Long id) {
        System.out.println("Am going on here...");
        System.out.println("id=="+id);
        System.out.println("fetching customers.."+id);
        Customer customer=customerRepository.getOne(id);
        System.out.println(customer);
        return customer;
    }

    // Create a new Customer
    @PostMapping("/customers")
    public Customer createCustomer(@Valid @RequestBody Customer customer) {
        return customerRepository.save(customer);
    }


}

我期望从ID中获取特定的客户是从邮递员(http://localhost:8080/getCustomer/1)传递过来的,但邮递员却给我以下错误消息:

  

此应用程序没有针对/ error的显式映射,因此您看到了   作为后备。星期二6月25日11:58:47 EAT 2019   意外错误(类型=内部服务器错误,状态= 500)。没有讯息   在以下位置提供了java.lang.NullPointerException   com.javadevjournal.customer.CustomerController.findCustomerById(CustomerController.java:43)     在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)在   org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)     在   org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)     在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)     在   org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)     在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)     在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)     在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)     在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:634)在   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:741)处   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)     在   org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)     在   org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)     在   org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:853)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1587)     在   org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)     在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     在   java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:617)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:745)

2 个答案:

答案 0 :(得分:2)

您已禁止在@Autowired上添加customerRepository

@Autowired
private CustomerService  customerService;
@Autowired
private CustomerRepository customerRepository;

答案 1 :(得分:0)

如上所述,您错过了@Autowired注释。还要注意,建议的摄取方式是抛出类构造函数或setters

@RestController
public class CustomerController {
    private final CustomerService  customerService;
    private final CustomerRepository customerRepository;

    @Autowire
    public CustomerController(CustomerService  customerService, CustomerRepository customerRepository) {
        customerService = customerService;
        customerRepository = customerRepository;
    }

    // the rest of your code
}

在没有@Autowired批注的情况下,这种DI也可以使用的很酷的东西)