【问题标题】:Spring Boot can't fetch and display Data from MySQL DatabaseSpring Boot 无法从 MySQL 数据库中获取和显示数据
【发布时间】:2019-08-01 16:43:54
【问题描述】:

我最近一直在处理一个 Spring Boot 项目,该项目以 JSON 格式更新和获取 MySQL 数据库中的数据,但是当我运行我的应用程序时,我有一个错误页面:

[我的浏览器上的错误截图][1] [1]:https://i.stack.imgur.com/CkYmr.png

我的实体类是:

package com.project.project.entities;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "products")
// why serializable ?? every entity in JPA is automatically-serializable,  connection between different networks
public class Product implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // assign a unique value to your identity field automatically
    private Long id;
    private String designation;
    private int price;
    private int quantity;
    private int category_id;

    // the owning side of the relationship, side of the foreign key

    @ManyToOne(fetch = FetchType.LAZY )// many products to one category
    @JoinColumn(name = "category_id" , insertable = false , updatable = false)
    // means that the product table will have a fk_column named...
    private Category category;


    // categoryId foreign key referencing to the primary key on Category
    // Double and Integer in case both variables are unknown -> Category constructor
    public Product(Long id, String designation, Integer price, Integer quantity, int categor_id) {
        this.id = id;
        this.designation = designation;
        this.price = price;
        this.quantity = quantity;
        this.category_id = category_id;
    }

我的仓库:

import com.project.project.entities.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface ProductRepository extends JpaRepository<Product,Long> {

}

我的服务组件:

import com.project.project.dao.ProductRepository;
import com.project.project.entities.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductService {

    @Autowired // establish injection
    private ProductRepository productRepository;

    // GET-ALL
    public List<Product> getAllProducts() {
        List<Product> products = new ArrayList<>();
        productRepository.findAll().forEach(products::add);
        return products;
    }

    // GET
    public Product getProduct(Long id) {
        return productRepository.getOne(id);
    }

    // POST
    public void addProduct(Product product){
        productRepository.save(product);
    }

    // PUT
    public void updateProduct(Long id, Product product) {
        product.setId(id);
        productRepository.save(product);
    }
    // DELETE
    public void deleteProduct(Long id){
        productRepository.deleteById(id);
    }
}

我的 REST 控制器是:

import com.project.project.entities.Product;
import com.project.project.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

public class ProductRestController {

    @Autowired
    ProductService productService;

   /* @Autowired // establish injection
    public ProductRepository productRepository;*/

    // GET-ALL
    @GetMapping(value = "/all")
    public @ResponseBody List<Product> getAllProducts() {
        return productService.getAllProducts();
    }


    /*@GetMapping(value = "/products/{id}")
    @ResponseBody
    public List<Product> getProducts(@RequestParam String designation) {
        return productRepository.findByDesignation(designation);
    }*/

    // GET
    @GetMapping(value = "/products/{id}")
    public Product getProduct(@PathVariable(name = "id") Long id) {
        return productService.getProduct(id);
    }

    // PUT
    @PutMapping(value = "/products/{id}")
    public void updateProduct(@PathVariable(name = "id") Long id, @RequestBody Product product) {
        productService.updateProduct(id, product);
    }

    // POST
    @PostMapping(value = "/products")
    public void save(@RequestBody Product product) {
        productService.addProduct(product);
    }

    // DELETE
    @DeleteMapping(value = "/products/{id}")
    public void delete(@PathVariable(name = "id") Long id) {
        productService.deleteProduct(id);
    }
}

我的 application.properties:

spring.datasource.url = jdbc:mysql://localhost:3306/sport_shop?serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = emisql
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
server.port = 9091
idea.spring.boot.filter.autoconfig=false 
spring.jpa.properties.hibernate.jdbc.time_zone=UTC

还有我的 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 http://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.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.project</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>project</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>

你们认为问题出在哪里?

【问题讨论】:

  • 请附上应用程序日志——这个错误页面什么也没说
  • 您的 tomcat 实例上的堆栈跟踪应该会告诉您问题出在哪里。
  • 我在您的控制器上看不到 @RestController 注释。根据屏幕截图,它无法找到您尝试访问的 api 路径。 404 表示找不到路径
  • 这解决了@RaviTeja的问题,谢谢!!!

标签: java spring hibernate spring-boot spring-mvc


【解决方案1】:

只需将@Controller 设置为控制器上的注释即可。

//imports

@Controller
public class ProductRestController {

    @Autowired
    ProductService productService;

    //GetMapping etc


}

您也可以使用@RestController 注释。在此处阅读有关差异的更多信息:

Difference between spring @Controller and @RestController annotation

【讨论】:

  • 这解决了@theshadog 的问题,另外我需要添加我的实体类中缺少的默认构造函数。感谢您的帮助!
  • 你也可以使用注释:projectlombok.org/features/constructor
猜你喜欢
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2020-01-11
  • 2019-12-06
  • 2023-04-05
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多