春季启动:无法发布到多对多关系

时间:2020-02-24 01:04:33

标签: java spring spring-boot spring-data-jpa spring-data

我有两个实体var Response = await YourRefitClient.DownloadPhoto(id); byte[] ByteArray = await Response.Content.ReadAsByteArrayAsync(); Meal处于@ManyToMany关系中。每个膳食计划可以有不同的膳食,并且每个膳食可以在多个膳食计划中。

Mealplan

@Entity
public class Meal {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private BigDecimal price;
    private String type;

@ManyToMany(mappedBy = "mealsPerWeek")
private List<Mealplan> mealplan;

由于我已经添加了ManyToMany关系,所以无法通过@Postmapping将其添加到API中来添加膳食。

MealController

@Entity
public class Mealplan {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private int week;

    @ManyToMany
    private List<Meal> mealsPerWeek;

MealRepository类扩展了JPARepository。

每当我想将某些东西发布到我的实体中时,例如:

@RestController
@RequestMapping("/meal")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MealController {

    @PostMapping
    public void addMeal(@RequestBody Meal meal) {
        mealRepository.save(meal);
    }

出现以下错误: { "id": 10, "name": "Test", "price": 3.50, "type": "with Meat" }

通过INSERT INTO添加照常工作。

3 个答案:

答案 0 :(得分:0)

根据您的实体映射,Id字段定义为自动生成。在您的请求Json中,Id作为10传递。您是要插入还是更新?您可以尝试在下面请求JSON并查看插入是否有效。

{
    "name": "Test",
    "price": 3.50,
    "type": "with Meat",
    "mealplan": []

}

答案 1 :(得分:0)

根据您的代码,由于您在实体Meal中使用了“ mappedBy”,因此它是映射实体,因此MealPlan成为所有者实体,即它负责维护关联。

您还需要创建另一个表,让我们调用 MealMapping 来存储Meal和MealPlan的映射,这些映射的字段为进餐ID和餐膳食ID。

现在,您需要在所有者实体中定义@JoinTable。

@Entity
public class Mealplan {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private int week;

@ManyToMany
@JoinTable(name="MealMapping", joinColumns={@JoinColumn(referencedColumnName="ID")}, 
inverseJoinColumns={@JoinColumn(referencedColumnName="ID")})  
private List<Meal> mealsPerWeek;
}

希望这会有所帮助。

此外,由于您已经在hibernate中定义了多对多关系,而不是在数据库表中定义了多对多关系,因此它可用于INSERT查询。因此,约束仅在尝试使用hibernate插入时适用。

答案 2 :(得分:0)

我为我解决了这个问题。我注意到,@GeneratedValue(strategy = GenerationType.AUTO)并未将ID字段设置为“自动递增”。我将其设置为@GeneratedValue(strategy = GenerationType.IDENTITY)并插入新数据,而无需使用这样的ID(如@Ravi Sharma所述):

{
    "name": "Test",
    "price": 3.50,
    "type": "with Meat"
}