【问题标题】:Get controller receives JSON with List<String> as null in Spring JPA获取控制器接收 JSON 与 List<String> 在 Spring JPA 中为 null
【发布时间】:2021-04-21 22:42:06
【问题描述】:

当我通过 Postman 发布一个新实体时,一切正常,我得到这个答案:

{
    "id": 3,
    "ingredients": [
        "Eggs",
        "Oil"
    ]
}

但是当我试图获取数据库中的现有实体时,List 成分返回为“null”:

[
    {
        "id": 3,
        "ingredients": null
    }
]

这是我的模型:

package com.petie.weeklyrecipesschedule.model;

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

@Entity
public class Recipe {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;
    @Embedded
    private List<String> ingredients;

    protected Recipe() {}

    public Recipe(String name, List<String> ingredients) {
        this.name = name;
        this.ingredients = ingredients;
    }

    //Getters and setters
    //toString()
} 

我的仓库

package com.petie.weeklyrecipesschedule.repository;

import com.petie.weeklyrecipesschedule.model.Recipe;
import org.springframework.data.jpa.repository.JpaRepository;

public interface RecipeRepository extends JpaRepository<Recipe, Long> {
}

还有我的控制器

package com.petie.weeklyrecipesschedule.controller;

import com.petie.weeklyrecipesschedule.model.Recipe;
import com.petie.weeklyrecipesschedule.repository.RecipeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/recipes")
public class RecipeController {

    @Autowired
    private RecipeRepository recipeRepository;

    public RecipeController(RecipeRepository recipeRepository) {
        this.recipeRepository = recipeRepository;
    }

    @GetMapping("/all")
    List<Recipe> getAll() {
        return recipeRepository.findAll();
    }

    @PostMapping("/post")
    Recipe newRecipe(@RequestBody Recipe recipe) {
        return recipeRepository.save(recipe);
    }
}

就依赖项而言,我使用的是 Spring Web、Spring Jpa 和 H2 数据库。

【问题讨论】:

    标签: json spring spring-data-jpa spring-data postman


    【解决方案1】:

    你也可以使用@ElementCollection:

    @ElementCollection
    @CollectionTable(name = "recipe_ingredients", 
            joinColumns = @JoinColumn(name = "recipe_id"))
    @Column(name = "ingredient_name")
    private List<String> ingredients;
    

    JPA 注解@Embedded 用于将一个类型嵌入到另一个实体中。

    注意:另外,您不需要在发帖请求中发送id,它会自动创建。

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2023-03-19
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多