Spring Boot生成RecipeIngredient关联表问题:需合并为单表求助
你遇到的两张表,一张是recipe_ingredient(对应你的RecipeIngredient实体),另一张是JPA自动生成的中间关联表(比如命名为recipe_ingredients)。原因是Recipe类里的@OneToMany注解未指定关联映射方式,JPA默认会为单向一对多关系生成额外的中间表来维护关联关系。
有两种方式可以去掉多余的中间表,只保留你需要的RecipeIngredient表:
方式一:双向关联(推荐)
通过在RecipeIngredient中添加Recipe的关联字段,将单向关系改为双向,让JPA直接用RecipeIngredient表的字段维护关联:
修改RecipeIngredient.java
添加与Recipe的关联字段:
@Data @Entity @AllArgsConstructor @NoArgsConstructor public class RecipeIngredient { @Id @GeneratedValue private int id; @ManyToOne private Ingredient ingredient; private String amount; // 添加Recipe关联 @ManyToOne private Recipe recipe; }
修改Recipe.java
更新@OneToMany注解,指定mappedBy指向RecipeIngredient中的recipe字段:
@OneToMany(mappedBy = "recipe", cascade=CascadeType.ALL) private List<RecipeIngredient> ingredients = new ArrayList<>();
修改后JPA会在RecipeIngredient表自动生成recipe_id外键列,不再生成中间表。
方式二:单向关联指定外键
如果不想改成双向关联,可直接在Recipe的@OneToMany里用@JoinColumn指定外键列,强制JPA把关联字段放在RecipeIngredient表中:
修改Recipe.java
@OneToMany(cascade=CascadeType.ALL) @JoinColumn(name = "recipe_id") // 指定外键列名,会生成在RecipeIngredient表内 private List<RecipeIngredient> ingredients = new ArrayList<>();
这种方式无需修改RecipeIngredient,JPA同样会在RecipeIngredient表添加recipe_id字段,不再生成中间关联表。
修改后重启应用,数据库只会保留RecipeIngredient对应的表(默认表名为recipe_ingredient,如需自定义可给RecipeIngredient添加@Table(name = "你的表名")),多余的中间表会被移除。
内容的提问来源于stack exchange,提问作者Hoon

