当前位置: 首页 > 知识库问答 >
问题:

在PostRequest中使用EntityManager时出错500

杜嘉木
2023-03-14

最终编辑:抱歉,我确信这篇文章很难理解,我正在为未来的子孙后代更新它。我从来没有弄清楚我的@持久性上下文注释有什么问题,我最终放弃了,只是转而使用CrudRepository。

我们的存储库接口从Crudepository实现:

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

这就是我的一个帖子集群,我仍然很好奇为什么我的@持久性上下文不知何故没有被选中,但是我所有的endpoint都设置正确,我仍然很想听到一个解释。我只是继续前进,使用了一个CrudRepository,虽然有多种方法可以做到这一点。

下面的原始帖子:

我正在尝试使用Spring Boot发出POST请求并存储有关我的汽车对象的信息。我遵循了一个我以前做过的指南,它很有效,所以我试图重新遵循这个指南和我之前的例子,但我似乎遗漏了一些东西。我得到了一个通用错误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中执行post请求时,我总是返回一个错误500,所以我将其从EntityManger更改为一个内存哈希映射,它工作正常,所以我确定是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指出的。我得到了一个空指针异常。以下是整个堆栈跟踪:

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]

编辑:我很确定这是我的身材。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个答案

谷梁迪
2023-03-14

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

@持久性上下文:持久性上下文处理一组实体,这些实体保存要在某些持久性存储(例如数据库)中持久化的数据。特别是,上下文知道一个实体相对于上下文和底层持久性存储可能具有的不同状态(例如托管、分离)。

 类似资料:
  • 问题内容: 我正在尝试获取特定目录中的文件列表,并计算目录中的文件数。我总是收到以下错误: 我的代码是: 我按照此处给出的代码示例进行操作。 我在Pyscripter上运行Python脚本,并且目录/ client_side /确实存在。我的python代码位于根文件夹中,并且有一个名为“ client_side”的子文件夹。有人可以帮我吗? 问题答案: 我决定将代码更改为: 并使用以下调用代码:

  • 无效的流头:0000002b at java.io.objectinPutStream.ReadStreamHeader(ObjectinPutStream.java:781)at java.io.objectinPutStream.(ObjectinPutStream.java:278)at servicerEquest.run(servicerEquest.java:24)at java.ut

  • 目前,我正在尝试将JWT身份验证集成到现有的Spring Boot Webflux项目中。作为模板,我使用了这篇媒体文章:https://medium.com/@ard333/authentication-and-authorization-using-jwt-on-spring-webflux-29b81f813e78。如果我将注释@EnableWebFluxSecurity放在我的WebSec

  • 在部署应用程序后,我得到HTTP404页面未找到错误我是新的jsp请有人帮助我。

  • 对象函数SOAPClient(options,fn){fn=this.fn=fn;options=this.options=_.extend({},defaults,options);var deferred;this.namespaces=“;this.methods=”;this.body=函数(options){return“”+“http://schemas.xmlsoap.org/soa