简体   繁体   English

本机查询问题 spring 数据 JPA 返回带有空对象的空 JSON 数组

[英]Problems with native query spring data JPA returns empty JSON array with empty objects

I'm learning spring 5 MVC with spring data JPA and sql queries我正在学习 spring 5 MVC 与 spring 数据 JPA 和 sql 查询

I'm trying to use a native query in my spring api restful example but when I run the project, my method returns an empty json object.我试图在我的 spring api 宁静示例中使用本机查询,但是当我运行该项目时,我的方法返回一个空的 json object。

My Model class我的 Model class

@Entity
@Table(name = "bicycle")
public class Bicycle
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @Column(name="name")
    private String name;
    
    @Column(name="year")
    private int year;
}

My repository class我的存储库 class

@Repository
public interface BicycleRepository extends CrudRepository<Bicycle, Long>
{
    @Query(value = "SELECT * from db_bicycles.bicycle", nativeQuery = true)
    public List<Bicycle> obtenerTodos();
}

My controller class我的 controller class

@RestController
@RequestMapping("/api")
public class BicycleController
{
    @Autowired
    private BicycleRepository bicycleRepository;
    
    //create get all bicycles
    @GetMapping("/bicycles")
    public List<Bicycle> getAllBicycles()
    {
        return bicycleRepository.obtenerTodos();
    }   
}

My application properties我的应用程序属性

spring.datasource.url=jdbc:mysql://localhost/db_bicycles?useUnicode=true&useJDBCCompilantTimeZoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true

This table have 2 rows.该表有 2 行。

在此处输入图像描述

  1. use getter/setter in your POJO class在你的 POJO 中使用 getter/setter class

  2. you need not to write query to retrieve all record.您无需编写查询来检索所有记录。 Simply you can make use of findAll() method which is available in crudeRepository.您只需使用 crudeRepository 中提供的 findAll() 方法即可。

bicycleRepository.findAll(); (will return list of your POJO class.) (将返回您的 POJO 列表 class。)

  1. make sure, there is data present in table.确保表中存在数据。 if not then make use of Setter/Construction如果没有,则使用 Setter/Construction

Injection to populate data.注入填充数据。 OR you can make a POST call to populate data in table using save() method.或者您可以使用 save() 方法进行 POST 调用以填充表中的数据。

If you are using lombok and Spring Tools Suite in your project, then try running Maven Clean and Maven Install.如果您在项目中使用 lombok 和 Spring Tools Suite,请尝试运行 Maven Clean 和 Maven Install。

mvn clean install

After that, you can run the project.之后,您可以运行该项目。 It should work.它应该工作。

The solution is to add the getter and setters, eclipse (STS) only add me the setters解决办法是加getter和setter,eclipse(STS)只加我setter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM