【发布时间】: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