在 PostRequest 中使用 EntityManager 时出现错误 500



>最终编辑:对不起,我确定这篇文章很难理解,我正在为将来的后代更新它。我从来没有弄清楚我的@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,有多种方法可以做到这一点。

原文如下:

我正在尝试使用 Spring Boot 发出 PostRequest 并存储有关我的 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

我的汽车控制器类:

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

我的应用程序.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/"
}

感谢您的任何帮助,非常感谢。

编辑:正如德米特里指出的那样,我现在意识到我实际上在日志中收到了一些有用的错误消息。我收到空指针异常。以下是整个堆栈跟踪:

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

相关内容

最新更新