【问题标题】:Getting 404 Error when calling a Spring Boot API调用 Spring Boot API 时出现 404 错误
【发布时间】:2021-05-04 12:09:56
【问题描述】:

我编写了一些请求映射并使用 JPA 将我的 Spring Boot 应用程序连接到 Postgresql DB。但是,当我尝试调用 API 时,我收到以下消息: {"timestamp":"2021-01-30T21:58:34.028+00:00","status":404,"error":"Not Found","message":"","path":"/api/v1/sessions"}。我尝试在调用 API 时打印一条消息并且它可以工作,所以我认为它可能与 JPA 连接有关? (我还使用 SQL Shell 测试了数据库和凭据是否良好,它们都可以)

我的模特:

@Entity(name = "sessions")
public class Session {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long session_id;

    private String session_name;
    private String session_description;
    private Integer session_length;

    @ManyToMany
    @JoinTable(
            name = "session_speakers",
            joinColumns = @JoinColumn(name = "session_id"),
            inverseJoinColumns = @JoinColumn(name = "speaker_id"))
    private List<Speaker> speakers;

我的控制器:

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

    @Autowired
    private SessionRepository sessionRepository;

    @GetMapping
    public List<Session> list() {
        System.out.println("Get method called");
        return sessionRepository.findAll();
    }

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

我的仓库:

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

最后,我的应用程序属性:

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

【问题讨论】:

    标签: java spring spring-boot jpa


    【解决方案1】:
        @GetMapping(value = "/{id}")<---remove Request mapping and also add the slash here
        public Session get(@PathVariable Long id) {
            return sessionRepository.getOne(id);
        }
    

    【讨论】:

    • 感谢您的建议!我已经尝试过了,但不幸的是我没有工作,这是所有 API url 的问题,不仅仅是那个。
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 2019-02-20
    • 2017-03-06
    • 2019-08-14
    • 2017-08-26
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多