OneToMany错误的主键列

时间:2019-02-13 13:51:38

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

我在应用程序中新创建的表有问题。我想在dashboard_id上设置主键,而我的关系有问题。为什么我得到这个?我有OneToMany,一个仪表板,很多小组。我该怎么办?它出什么问题了? 在Dashboard_groups表中,我将groups_id作为PK,并且我想要仪表板ID。

@ManyToOne(targetEntity = Dashboard.class, fetch = FetchType.EAGER)
@JoinTable(name = "dashboard_groups", joinColumns = {@JoinColumn(name = "groups_id")},
        inverseJoinColumns = {@JoinColumn(name = "dashboard_id", referencedColumnName = "id")})
@JsonBackReference(value = "group- dashboard")
private Dashboard dashboard;
@OneToMany(mappedBy = "dashboard", cascade = CascadeType.ALL)
    @JsonManagedReference(value = "groups- dashboard")
    private List<Group> groups= new ArrayList<>();


2 个答案:

答案 0 :(得分:2)

最简单的方法是不使用联接表。只需在Group中使用外键即可。

@Entity
class Dashboard {

    @OneToMany(mappedBy = "dashboard", cascade = CascadeType.ALL)
    private List<Group> groups;

}

@Entity
class Group{

    @ManyToOne(fetch = FetchType.LAZY)
    private Dashboard dashboard;

}

如果要使用联接表,则不应使用mappedBy

@Entity
class Dashboard {

    @OneToMany(cascade = CascadeType.ALL)
    private List<Group> groups;

}

@Entity
class Group{


}

答案 1 :(得分:1)

这部分:joinColumns = {@JoinColumn(name = "groups_id")}缺少referencedColumnName,您需要指定它,就像下一个@JoinColumn

inverseJoinColumns = {@JoinColumn(name = "dashboard_id", referencedColumnName = "id")}