get controller在spring jpa中接收list< string>为null的json

yhived7q  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(305)

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

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

但是,当我试图获取数据库中现有的实体时,listcomponents返回为“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);
    }
}

至于依赖关系,我使用的是springweb、springjpa和h2数据库。

gblwokeq

gblwokeq1#

你也可以使用 @ElementCollection :

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

jpa注解 @Embedded 用于将类型嵌入到另一个实体中。
注意:此外,您不需要发送 id 在您的post请求中,它将自动创建。

相关问题