简体   繁体   中英

Error 500 using EntityManager in PostRequest

FINAL EDIT: Sorry I'm sure this post is very hard to follow, I'm updating it for future posterity. I never figured out what is the issue with my @PersistenceContext annotation, I ended up giving up and just moved on to using a CrudRepository instead.

our repository interface that implements from CrudRepository:

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

Make a service Interface (not necessary but it's better practice):

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

make the implementing subclass @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;
    }
}

So that's my cluster of a post, I'm still curious as to why my @PersistenceContext wasn't picked up on somehow, but all my endpoints were setup correctly, I would still love to hear an explanation. I just moved on and used a CrudRepository though, there are multiple ways to do this.

Original post below:

I am trying to make a PostRequest and store information about my Car object using Spring Boot. I was following a guide where I have done this previously and it worked, so I'm trying to refollow that guide and my prior example, but I seem to be missing something. I get a generic error 500, and I'm not sure where to go from here.

my Car class:

@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

My CarController class:

@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;
    }
}

My Car 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);
    }
}

My 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

In my prior examples that work, I have used this same application.yml , and I double checked that I do not have a password set, so I have omitted that field.

I made a database and table. The following SQL code makes the table. Making the table in unnecessary as the table is automatically generated, I dropped the table and just had the database exist at the end of all this:

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;

My main SpringBootApplication class is very straightforward:

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);
    }

}

I was wondering if my table was set up incorrectly somehow, so I copy pasted my prior working example and it too gave me an error 500, so I do not think my table is incorrect because I'm certain my prior table for a different Application works.

When I do my post request in PostMan, I always get back an error 500, so I changed it from EntityManger to just an in memory HashMap, and it works fine, so I'm certain it's the EntityManager that is the problem.

Is there some component that I'm missing here, or is something I've done wrong? I have spent far too much time on this, but it looks like I'm following my past example identically, but obviously not.

My post request:

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

and the response is pretty useless, it just says

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

Thank you for any help, it's greatly appreciated.

EDIT: I now realize I am actually getting some useful error message in the logs, as Dmitriy pointed out. I am getting a NullPointer Exception. Here is the entire stacktrace:

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]

EDIT: I'm pretty sure it's my build.gradle that is the problem, because I don't see what else it could be. I'm surprised that it even compiles if that's the problem to be honest, but here it is anyways:

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"
])

In your code for the class CarsRepository.java , you have provided the annotation @Transactional on the method .Try using it like below :

@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: A persistence context handles a set of entities which hold data to be persisted in some persistence store (eg a database). In particular, the context is aware of the different states an entity can have (eg managed, detached) in relation to both the context and the underlying persistence store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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