简体   繁体   English

Spring 引导:数据库保存值为 Null

[英]Spring Boot: Database Saving Value as Null

I'm new to Spring Boot.我是 Spring 引导的新手。

I'm building a Rest API using H2, JPA, Lombok, Spring Web and DevTools. I'm building a Rest API using H2, JPA, Lombok, Spring Web and DevTools.

I'm having the following problem: When inserting a value in the database it receives an id (ok, great) and when saving another data it saves it as null.我遇到了以下问题:在数据库中插入一个值时,它会收到一个 id(好的,很好),当保存另一个数据时,它将它保存为 null。

My application.properties:我的应用程序属性:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.generate-unique-name=false

My controller:我的 controller:

package com.b.c.controller;

import java.util.List;

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

import com.b.c.model.Receita;
import com.b.c.repository.ReceitaRepository;
import lombok.AllArgsConstructor;

@RestController
@AllArgsConstructor 
public class ReceitaController {
    
    @Autowired
    private ReceitaRepository receitaRepository;

    @GetMapping("/status")
    public List<Receita> getStatus() {
        return receitaRepository.findAll();
    }
    
    @PostMapping("/cadastrar")
    public Receita setUser(@RequestBody Receita receita) {
        return receitaRepository.save(receita);
    }

}

My model:我的 model:

package com.b.c.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "receitas")
public class Receita {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name="nome")
    private String nome;

}

My repository:我的存储库:

package com.b.c.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.b.c.model.Receita;

@Repository
public interface ReceitaRepository extends JpaRepository<Receita, Long>{

}

When making the post request with the payload in json it generates the id and saves the value of "nome" as null.当使用 json 中的负载发出 post 请求时,它会生成 id 并将“nome”的值保存为 null。

I manually entered test values into the database and when doing "receitaRepository.findAll();"我手动将测试值输入到数据库中,并且在执行“receitaRepository.findAll();”时it also returns "{}" with no value even after manually entering the values into the database.即使手动将值输入数据库后,它也会返回没有值的“{}”。

So when inserting the values by the post method it is saved as null and when getting the values from the database to return a get it also displays as null, returning empty braces "{}".因此,当通过 post 方法插入值时,它被保存为 null,当从数据库中获取值以返回 get 时,它也显示为 null,返回空括号“{}”。

Before saving the value you can validate the RequestBody.在保存值之前,您可以验证 RequestBody。 For this, you can use @Valid annotation along with @RequestBody.为此,您可以将@Valid 注释与@RequestBody 一起使用。 It will tell Spring to process validation before making an actual method call.它将告诉 Spring 在进行实际方法调用之前处理验证。 In case validation fails, Spring will throw a MethodArgument NotValidException which, by default, will return a 400 (Bad Request) response.如果验证失败,Spring 将抛出 MethodArgument NotValidException,默认情况下将返回 400(错误请求)响应。 In POST or PUT requests, when we pass JSON payload, Spring automatically converts it into a Java object and now it can validate the resulting object. In POST or PUT requests, when we pass JSON payload, Spring automatically converts it into a Java object and now it can validate the resulting object. You can also mark your Model with the proper validation annotations.您还可以使用适当的验证注释标记您的 Model。

@PostMapping("/cadastrar")
public Receita setUser(@Valid @RequestBody Receita receita) {
    return receitaRepository.save(receita);
}

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

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