创建包含多个主键的连接表时出现问题。下面是我的表结构:
以下是我的JPA实施:
@Entity
@Table(name = "label")
public class Label {
@Id
@Column(name = "tenant_id")
private String tenant_id;
@Id
@Column(name = "label_id")
private String label_id;
@JsonIgnore
@ManyToMany(targetEntity = Report.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "label_id"), inverseJoinColumns = @JoinColumn(name = "report_id"))
private Set<Report> reports;
}
@Entity
@Table(name = "report")
public class Report {
@Id
@Column(name = "tenant_id")
private String tenant_id;
@Id
@Column(name = "report_id")
private String report_id;
@column(name = "created_by")
private String created_by;
@JsonIgnore
@ManyToMany(targetEntity = Label.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "report_id"), inverseJoinColumns = @JoinColumn(name = "label_id"))
private Set<Label> labels;
}
这很好用,但是当我尝试将tenant_id
添加到混合中时如下:
Label.java编辑:
@JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "label_id"), inverseJoinColumns = { @JoinColumn(name = "report_id"), @JoinColumn(name = "tenant_id") })
private Set<Report> reports;
Report.java编辑:
@JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "report_id"), inverseJoinColumns = { @JoinColumn(name = "label_id"), @JoinColumn(name = "tenant_id") })
private Set<Label> labels;
我收到错误消息“A Foreign key refering has the wrong number of column. should be 1”
。据我了解,这是因为我只有一个名为Report的主键和每个标签,因此我无法将tenant_id
映射为JoinColumn
。但是,我想知道,当设置tenant_id
和report_id
时,有没有办法设置label_id
?任何帮助,将不胜感激。谢谢!
编辑:实体中的@Id字段在报告和标签类中都是tenant_id和id。
答案 0 :(得分:0)
对不起,我无法尝试这一点,但从头顶来看,就是这样的。有一些东西需要修复,比如完整的注释属性,因为列名和类成员不一样,但这就是想法。 :)
更多信息here
报告类
@Entity
public class Report {
@Id
private Integer id;
@Column
private String createdBy;
@Column
private String tenantId;
@OneToMany
private List<Tagging> taggings = new ArrayList<>();
// getter and setters
}
标签类
@Entity
public class Label {
@Id
private Integer id;
@Column
private String tenantId;
@OneToMany
private List<Tagging> taggings = new ArrayList<>();
// getter and setters
}
标记类
@Entity
public class Tagging {
@EmbeddedId
private TaggingId id;
@OneToMany
private Report report;
@OneToMany
private Label label;
// getter and setters
}
@Embeddable
class TaggingId {
private Integer reportId;
private String labelId;
private String tenantId;
// getter and setters
}