JPA,与OneToMany关系挣扎

时间:2016-10-26 08:39:47

标签: hibernate jpa

我有两个MySQL表,第一个......

食谱

  • id(int)
  • user_id(int)
  • recipe_id(int)
  • created_at(datetime)

配方

  • id(int)
  • title(varchar)
  • 等等

食谱表的目的是跟踪用户添加到食谱中的食谱。

我已经创建了一个CookBook JPA实体,我试图将配方拉进每个食谱行。

@Entity
@Table(name="cookbook")
public class CookBook {

    @Id
    @GeneratedValue
    private int id;

    @Column(name="user_id")
    private int userId;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name = "recipe_id", referencedColumnName = "id")
    private List<Recipe> recipes;

    @Column(name="created_at", columnDefinition = "DATETIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;

    /* Getters and setters */
}

问题在于,无论我怎样尝试,我都会遇到错误。有了以上我得到了;

Unknown column 'recipes0_.recipe_id' in 'field list'

这当然是正确的,因为食谱表不包含该字段。所以我改变了CookBook中的关系;

@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "recipe_id")
private List<Recipe> recipes;

当我这样做时,我的Spring Boot应用程序不会运行,它会显示错误;

Unable to find column with logical name: recipe_id in org.hibernate.mapping.Table(cookbook) and its related supertables and secondary tables

有人能指出我出错的地方吗?

如果有帮助,我会看到最终的SQL看起来像这样;

SELECT * FROM cookbook INNER JOIN recipe ON cookbook.recipe_id = recipe.id

1 个答案:

答案 0 :(得分:0)

对于有此问题的其他人。上面的评论是正确的,我做错了。

最后,我通过将关系放在User实体中解决了问题,因此我可以使用;

访问每个用户的cookbook配方
user.getCookBookRecipes();

这是我最终在我的用户实体中使用的关系。

/* Cookbook */
@ManyToMany
@JoinTable(
    name="cookbook",
    joinColumns=@JoinColumn(name="user_id", referencedColumnName="id"),
    inverseJoinColumns=@JoinColumn(name="recipe_id", referencedColumnName="id"))
@JsonIgnore
private List<Recipe> cookbookRecipes;
相关问题