繁体   English   中英

映射和管理实体的问题,Hibernate

[英]Problem with mapping and managing entity, Hibernate

我有两个实体:Dish 和 Ingredient。 我想在菜肴中添加配料。 当我使用@ManyToMany关系执行此操作时(我添加、删除、获取所有带有配料表的菜肴 - 我的端点有效),但现在我想在跨表DishIngredient中添加额外的列。

所以我所做的是:

  • 删除@ManyToMany ,添加@OneToMany / @ManyToOne
  • 添加了交叉表作为实体(java类)并添加了额外的字段(作为我在db中的额外列)

现在,当我想通过 id 获取所有菜肴或单个菜肴时,我得到错误:

2020-06-25 17:01:25.995 ERROR 8528 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : BŁĄD: column ingredient1_.id does not exist
  Pozycja: 406
2020-06-25 17:01:26.000  WARN 8528 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not extract ResultSet; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not extract ResultSet (through reference chain: java.util.ArrayList[0]->.springbootdemo.dish.domain.Dish["dishIngredient"])]

我的代码在这里,在分支上: https://github.com/rhquee/MealsOrganizerApp/tree/mapping_many_to_many_extra_column

我的数据库是:

在此处输入图像描述

如何管理这个跨表(跨类)?

更改 hibernate 配置

spring.jpa.hibernate.ddl-auto=none

经过

spring.jpa.hibernate.ddl-auto=create-drop

每次构建应用程序时,它都会创建架构并销毁以前的数据。 对于初始项目构建来说,这是一个很好的选择。

在我看来,最好的方法是通过 Hibernate 创建数据库模式。 Firstly change spring.jpa.hibernate.ddl-auto=none to spring.jpa.hibernate.ddl-auto=update or create-drop . 然后在dishingredient列上删除 model DishIngredient中的@id注释,并将ReferencedColumn添加到@JoinColumn 您还需要将 repo 和服务中的所有基本方法添加到 model DishIngredient

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM