首页 > 解决方案 > GET 请求返回 {} 但 db 表有条目(Spring boot+JPA+MySQL)

问题描述

我试图将表中的所有条目作为 JSON 对象接收,获取请求显示“200 OK”,但它返回 [{}]。

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "man")
public class User {
    @Id
    @GeneratedValue
    @Column(name = "man_id")
    private Integer id;
    @Column(name = "man_name")
    private String name;
    @Column(name = "salary")
    private Double salary;
    @Column(name = "reg")
    private LocalDateTime dateTime;
}
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDAO extends JpaRepository<User,Integer> {
}

服务层

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    private final UserDAO userDAO;

    @Autowired
    public UserService(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public List<User> findAll(){
        return userDAO.findAll();
    }
}

控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/man")
public class UserControl {

    private final UserService userService;

    @Autowired
    public UserControl(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/all")
    public List<User> findAll(){
        return userService.findAll();
    }
}

应用程序.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: onionnetwork

    jpa:
      hibernate.dll-auto: update
      generate: true
      show-sql: true

使用的依赖项: starter-web , stater-jpa , mysql 连接器

注意:我目前正在通过 YouTube 教程学习 Spring Boot,所以会有一些令人毛骨悚然的编程实践。如果你们可以帮助我提供评论和良好的资源来学习 Spring-boot,非常感谢。:)

标签: javamysqlspring-bootspring-data-jpa

解决方案


推荐阅读