【问题标题】:Update and Delete not working on Spring Boot Application更新和删除在 Spring Boot 应用程序上不起作用
【发布时间】:2020-05-12 01:09:34
【问题描述】:

观看在线课程后,我试图创建一个简单的 CRUD spring boot 应用程序。但是 updatedelete 功能不起作用。 GETPOST 有效,但 PUTDELETE 无效。我在最后插入了邮递员响应的屏幕截图。我在邮递员上收到 200 OK 回复,但为什么它不起作用?另外,我正在使用 PostgreSQL 作为数据库。请帮忙。

会话控制器(deleteupdate 是最后两个方法):

package com.organizer.conferencedemo.controllers;

import com.organizer.conferencedemo.models.Session;
import com.organizer.conferencedemo.repositories.SessionRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/v1/sessions")
public class SessionsController {

    @Autowired
    private SessionRepository sessionRepository;

    @GetMapping
    public List<Session> list() {
        return sessionRepository.findAll();
    }

    @GetMapping
    @RequestMapping("{id}")
    public Session get (@PathVariable Long id) {
        return sessionRepository.getOne(id);
    }

    @PostMapping
    public Session create(@RequestBody final Session session) {
        return sessionRepository.saveAndFlush(session);
    }

    @RequestMapping(value = {"id"}, method = RequestMethod.DELETE)
    public void delete(@PathVariable Long id)
    {

        sessionRepository.deleteById(id);
    }

    @RequestMapping(value = {"id"}, method = RequestMethod.PUT)
    public Session update(@PathVariable Long id, @RequestBody Session session)
    {
        Session existingSession = sessionRepository.getOne(id);
        BeanUtils.copyProperties(session, existingSession, "session_id");
        return sessionRepository.saveAndFlush(existingSession);
    }
}

会话存储库:

package com.organizer.conferencedemo.repositories;

import com.organizer.conferencedemo.models.Session;
import org.springframework.data.jpa.repository.JpaRepository;

public interface SessionRepository extends JpaRepository<Session, Long> {
}

application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/conferencedb
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = none
spring.jpa.hibernate.show-sql = true

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

spring.datasource.initialization-mode=always
spring.datasource.initialize=true
spring.datasource.continue-on-error=true

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.organizer</groupId>
    <artifactId>conference-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>conference-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

构建 cmets:

:: Spring Boot ::       (v2.1.10.RELEASE)

2020-01-26 16:36:58.221  INFO 10272 --- [           main] c.o.c.ConferenceDemoApplication          : Starting ConferenceDemoApplication on hp with PID 10272 (started by User in C:\Users\User\Documents\1. PERSONAL\8. IND PROJECTS\conference-demo\conference-demo)
2020-01-26 16:36:58.264  INFO 10272 --- [           main] c.o.c.ConferenceDemoApplication          : No active profile set, falling back to default profiles: default
2020-01-26 16:37:05.282  INFO 10272 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-01-26 16:37:05.979  INFO 10272 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 580ms. Found 2 repository interfaces.
2020-01-26 16:37:10.887  INFO 10272 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8550c927] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-01-26 16:37:14.000  INFO 10272 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-01-26 16:37:14.550  INFO 10272 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-01-26 16:37:14.551  INFO 10272 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.27]
2020-01-26 16:37:15.215  INFO 10272 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-01-26 16:37:15.216  INFO 10272 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 16441 ms
2020-01-26 16:37:28.898  INFO 10272 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-01-26 16:37:41.464  INFO 10272 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-01-26 16:37:44.305  INFO 10272 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2020-01-26 16:37:46.371  INFO 10272 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.13.Final}
2020-01-26 16:37:46.382  INFO 10272 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2020-01-26 16:37:48.374  INFO 10272 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-01-26 16:37:49.043  INFO 10272 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2020-01-26 16:37:50.035  INFO 10272 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2020-01-26 16:37:50.070  INFO 10272 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@571a01f9
2020-01-26 16:38:01.918  INFO 10272 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-01-26 16:38:09.233  INFO 10272 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-01-26 16:38:09.364  WARN 10272 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-01-26 16:38:10.388  INFO 10272 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-01-26 16:38:10.394  INFO 10272 --- [           main] c.o.c.ConferenceDemoApplication          : Started ConferenceDemoApplication in 79.401 seconds (JVM running for 85.94)
2020-01-26 16:38:37.417  INFO 10272 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-26 16:38:37.417  INFO 10272 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-01-26 16:38:37.436  INFO 10272 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 19 ms

创建新会话

]

更新该会话: 更新后,响应应包含更新的会话名称和描述。但它显示的是旧的上一个会话名称和描述。

]

删除该会话

对于删除它不应该返回任何东西。但它会返回该会话 ID 的详细信息。

【问题讨论】:

  • 您的删除方法返回 void,并且在您的邮递员删除请求中,您显示的是返回的正文。
  • 更新和删除不是。更新后,响应应包含更新的会话名称和描述。但它显示的是旧的上一个会话名称和描述。对于删除它不应该返回任何东西。但它正在返回该会话 ID 的详细信息。 @Thomas Andolf
  • 控制器中的代码属于一个服务,应该是@Transactional。您正在修改数据而没有事务。
  • 所以我应该给@Transactional注解更新和删除方法? @M。 Deinum

标签: java spring hibernate spring-boot jpa


【解决方案1】:

您必须将路径变量参数括在映射注释中的括号中才能正常工作,否则 PUTDELETE 请求将不匹配并因此被忽略。

例如:

@RequestMapping(value = "{id}", method = RequestMethod.PUT)
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)

【讨论】:

  • 您好,感谢您的回答。让我看看这是否有效。 :)
  • 这正是问题所在!非常感谢您解决这个问题。我太瞎了,看不见! :) @Bohdan Levchenko
猜你喜欢
  • 1970-01-01
  • 2016-11-12
  • 2018-03-15
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 2018-12-01
相关资源
最近更新 更多