在PostRequest中使用EntityManager的错误500

时间:2019-06-30 18:20:25

标签: java spring-boot post entitymanager

最终编辑:对不起,我确定这篇文章很难理解,我正在对其进行更新以备后继。我没弄清楚@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"
])

1 个答案:

答案 0 :(得分:-1)

在类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:持久性上下文处理一组实体   其中包含要保留在某些持久性存储中的数据(例如   数据库)。特别是,上下文知道不同的状态   实体相对于两个实体可以具有(例如,托管,分离)   上下文和基础持久存储。