[英]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. 我从来没有弄清楚
@PersistenceContext
注释是什么问题,我最终放弃了,只是继续使用CrudRepository。
our repository interface that implements from CrudRepository: 从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:
@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. 所以这就是我的帖子集,我仍然很好奇为什么我的
@PersistenceContext
没有被选中,但是我所有的端点都正确设置了,我还是很想听听一个解释。 I just moved on and used a CrudRepository though, there are multiple ways to do this. 我只是继续使用CrudRepository,但是有多种方法可以做到这一点。
Original post below: 原始帖子如下:
I am trying to make a PostRequest and store information about my Car object using Spring Boot. 我正在尝试发出一个PostRequest并使用Spring Boot存储有关我的Car对象的信息。 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.
我收到一般错误500,但我不确定从这里到哪里。
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: 我的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;
}
}
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: 我的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. 在之前的有效示例中,我使用了相同的
application.yml
,并且再次检查了我是否设置了密码,因此省略了该字段。
I made a database and table. 我做了一个数据库和表。 The following SQL code makes the table.
下面的SQL代码构成了表格。 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: 我的主要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);
}
}
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. 我想知道我的表是否以某种方式设置不正确,所以我复制粘贴了我先前的工作示例,它也给我一个错误500,所以我不认为我的表是错误的,因为我确定我的先前表是用于其他应用程序作品。
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. 当我在PostMan中执行发帖请求时,我总是会返回错误500,因此我将其从EntityManger更改为仅在内存中的HashMap,它可以正常工作,因此我确定是EntityManager出了问题。
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. 编辑:正如Dmitriy所指出的,我现在意识到我实际上在日志中收到了一些有用的错误消息。 I am getting a NullPointer Exception.
我收到NullPointer异常。 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. 编辑:我很确定这是我的build.gradle的问题,因为我不知道还有什么可能。 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 : 在
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: A persistence context handles a set of entities which hold data to be persisted in some persistence store (eg a database).
@PersistenceContext:持久性上下文处理一组实体,这些实体保存要持久存储在某个持久性存储区(例如数据库)中的数据。 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.
特别地,上下文意识到实体可以相对于上下文和基础持久性存储具有不同的状态(例如,管理,分离)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.