簡體   English   中英

在PostRequest中使用EntityManager的錯誤500

[英]Error 500 using EntityManager in PostRequest

最后編輯:對不起,我確定這篇文章很難理解,我正在對其進行更新以備后用。 我從來沒有弄清楚@PersistenceContext注釋是什么問題,我最終放棄了,只是繼續使用CrudRepository。

從CrudRepository實現的我們的存儲庫接口:

public interface RepositoryCar extends CrudRepository<Car, Long> {
}

創建服務接口(不是必需的,但這是更好的做法):

public interface ServiceInterface {
    Car addCar(Car car);
    Car findCar(long carId);
}

使實現子類為@Service:

@Service
@Transactional
public class ServiceCar implements ServiceInterface{
    //autowire this so it can instantiate your CrudRepository class.
    @Autowired
    RepositoryCar repositoryCar;


    public Car addCar(Car car) {
        return repositoryCar.save(car);
    }

    public Car findCar(long carId) {
        Optional<Car> present=repositoryCar.findById(carId);
        if(present.isPresent())
        {
            return present.get();
        }
        else
            return null;
    }
}

所以這就是我的帖子集,我仍然很好奇為什么我的@PersistenceContext沒有被選中,但是我所有的端點都正確設置了,我還是很想聽聽一個解釋。 我只是繼續使用CrudRepository,但是有多種方法可以做到這一點。

原始帖子如下:

我正在嘗試發出一個PostRequest並使用Spring Boot存儲有關我的Car對象的信息。 我遵循的是以前做過的指南,但是起了作用,因此我試圖重新閱讀該指南和之前的示例,但是似乎缺少一些東西。 我收到一般錯誤500,但我不確定從這里到哪里。

我的汽車課:

@Entity
@Table(name = "cars")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String make;
    private String model;
    private String color;
    private int year;

    public Car(String make, String model, String color, int year) {
        this.make = make;
        this.model = model;
        this.color = color;
        this.year = year;
    }
    //getters and setters

我的CarController類:

@RestController
@RequestMapping("/cars")
public class CarsController {
    CarsRepository repository;

    public CarsController(CarsRepository repository) {
        this.repository = repository;
    }

    @PostMapping
    public Car addCar(@RequestBody Car car) {
        repository.addCar(car);
        return car;
    }

    @GetMapping
    public CarsRepository getCars() {
        return repository;
    }
}

我的汽車資料庫:

@Repository
public class CarsRepository {

    @PersistenceContext
    EntityManager entityManager;

    @Transactional
    public void addCar(Car car) {

        entityManager.persist(car);
    }

    public Car find(Long id) {
        return entityManager.find(Car.class, id);
    }
}

我的Application.yml:

spring:
  jpa:
    generate-ddl: true
    properties.hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect

  datasource:
    url: jdbc:mysql://localhost:3306/cars?useSSL=false
    username: root

在之前的有效示例中,我使用了相同的application.yml ,並且再次檢查了我是否設置了密碼,因此省略了該字段。

我做了一個數據庫和表。 下面的SQL代碼構成了表格。 由於該表是自動生成的,因此無需使用該表,因此我刪除了該表,只是在所有這些操作的結尾都存在數據庫:

CREATE TABLE car (
  id         BIGINT(20) NOT NULL AUTO_INCREMENT,
  make       VARCHAR(20),
  model      VARCHAR(20),
  color      VARCHAR(20),
  year       INT,
  PRIMARY KEY (id)
)
  ENGINE = innodb
  DEFAULT CHARSET = utf8;

我的主要SpringBootApplication類非常簡單:

package study.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

我想知道我的表是否以某種方式設置不正確,所以我復制粘貼了我先前的工作示例,它也給我一個錯誤500,所以我不認為我的表是錯誤的,因為我確定我的先前表是用於其他應用程序作品。

當我在PostMan中執行發帖請求時,我總是會返回錯誤500,因此我將其從EntityManger更改為僅在內存中的HashMap,它可以正常工作,因此我確定是EntityManager出了問題。

我是否在這里缺少某些組件,或者我做錯了什么? 我花了太多時間在此上,但似乎我正在按照過去的示例進行同樣的操作,但顯然不是。

我的帖子要求:

{
    "make" : "make",
    "model" : "model",
    "color" : "blue",
    "year" : 2000
}

它的回應是毫無用處的,它只是說

{
    "timestamp": "2019-06-29T03:29:06.110+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "No message available",
    "path": "/cars/"
}

感謝您的幫助,我們非常感謝。

編輯:正如Dmitriy所指出的,我現在意識到我實際上在日志中收到了一些有用的錯誤消息。 我收到NullPointer異常。 這是整個堆棧跟蹤:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
        at study.example.CarsRepository.addCar(CarsRepository.java:19) ~[main/:na]
        at study.example.CarsController.addCar(CarsController.java:23) ~[main/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_211]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:685) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_211]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_211]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_211]

編輯:我很確定這是我的build.gradle的問題,因為我不知道還有什么可能。 說實話,我很驚訝它甚至可以編譯,但是無論如何這里都是這樣:

buildscript {
    ext {
        springBootVersion = "2.0.6.RELEASE"
        springVersion = "5.0.10.RELEASE"
        hibernateVersion = "5.2.17.Final"
        slf4jVersion = "1.7.25"
        junitVersion = "4.12"
        mysqlVersion = "5.1.40"
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"

    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

repositories {
    mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
    compile "com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.7.0"
    compile("mysql:mysql-connector-java:6.0.6")
    compile "org.springframework.boot:spring-boot-starter-tomcat"
    compile "org.hibernate:hibernate-core:$hibernateVersion"
    compile "org.slf4j:slf4j-api:$slf4jVersion"
    testCompile("org.springframework.boot:spring-boot-starter-test:$springBootVersion")

}

springBoot {
    buildInfo()
}

bootRun.environment([
        "WELCOME_MESSAGE": "hello"
])

CarsRepository.java類的代碼中,您在方法上提供了@Transactional注釋,請嘗試使用它,如下所示:

@Repository
@Transactional
public class CarsRepository {

    @PersistenceContext
    EntityManager entityManager;

    public void addCar(Car car) {

        entityManager.persist(car);
    }

    public Car find(Long id) {
        return entityManager.find(Car.class, id);
    }
}

@PersistenceContext:持久性上下文處理一組實體,這些實體保存要持久存儲在某個持久性存儲區(例如數據庫)中的數據。 特別地,上下文意識到實體可以相對於上下文和基礎持久性存儲具有不同的狀態(例如,管理,分離)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM