【问题标题】:Problem with mapping and managing entity, Hibernate映射和管理实体的问题,Hibernate
【发布时间】:2020-10-16 03:22:12
【问题描述】:

我有两个实体: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

我的数据库是:

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

【问题讨论】:

  • DishIngredient.java -> 从 Dish & Ingredient 实例变量中删除 @Id。添加一个新变量@Id private Integer id; 否则你必须使用@EmbeddedId,@johnmule

标签: java hibernate one-to-many hibernate-mapping


【解决方案1】:

在我看来,最好的方法是通过 Hibernate 创建数据库模式。首先将spring.jpa.hibernate.ddl-auto=none 更改为spring.jpa.hibernate.ddl-auto=updatecreate-drop。然后在dishingredient 列上删除模型DishIngredient 中的@id 注释,并将ReferencedColumn 添加到@JoinColumn。您还需要在 repo 和 service 中添加所有必要的方法来建模 DishIngredient

【讨论】:

    【解决方案2】:

    更改休眠配置

    spring.jpa.hibernate.ddl-auto=none
    

    通过

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

    它会在您每次构建应用程序时创建架构并销毁以前的数据。 这是初始项目构建的不错选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2011-07-31
      • 2021-10-24
      • 2011-11-15
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多