当我通过 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数据库。
1条答案
按热度按时间gblwokeq1#
你也可以使用
@ElementCollection
:jpa注解
@Embedded
用于将类型嵌入到另一个实体中。注意:此外,您不需要发送
id
在您的post请求中,它将自动创建。