我有2个表与多对多关联
表A
:
ID (PK), A_NAME
表B
:
ID (PK), B_CODE(UNIQUE), B_NAME
表A_B
:
ID (PK), ID (FK to table A(ID)), CODE (FK to table B(B_CODE))
我想使用注释为这种多对多的关系配置一个hibernate类。问题是表A_B
有CODE
(FK到表B(B_CODE))
但B_CODE
不是主键。我以前的尝试都失败了。
答案 0 :(得分:1)
最佳解决方案:
表格方案:
@Entity
@Table(name = "SCHEME")
public class Scheme implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private BigInteger id;
@NaturalId
@Column(name = "SCHEME_NAME")
private String schemeName;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "POSITION_SCHEME",
joinColumns = {
@JoinColumn(name = "SCHEME_ID", referencedColumnName = "ID")},
inverseJoinColumns = {
@JoinColumn(name = "POSITION_CODE", referencedColumnName = "CODE")}
)
private Set<Position> positions = new HashSet<>();
// getter & setter
}
表位置:
@Entity
@Table(name = "POSITION")
public class Position implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private BigInteger id;
@NaturalId
@Column(name = "CODE")
private String code;
@Column(name = "POSITION_DESCRIPTION")
private String positionDescription;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "POSITION_SCHEME",
joinColumns = {
@JoinColumn(name = "POSITION_CODE", referencedColumnName = "CODE")},
inverseJoinColumns = {
@JoinColumn(name = "SCHEME_ID", referencedColumnName = "ID")}
)
private Set<Scheme> schemes = new HashSet<>();
}