我已經創建了兩個使用Hibernate作爲具有ManyToMany關係的提供程序的JPA實體(Client,InstrumentTraded)。讓Hibernate爲MySQL生成表之後,似乎ManyToMany關係表不包含這兩個外鍵的主鍵。這允許多對多表中的重複記錄,這不是所需的結果。使用JPA與Hibernate提供程序的ManyToMany關係不會創建主鍵
表生成:
client(id,name)
instrument_traded(id,name)
client_instrument_traded(FK client_id, FK instrument_traded_id)
優選表:
client_instrument_traded(PK,FK client_id, PK,FK instrument_traded_id)
實體:
@Entity
public class Client extends AbstractEntity<Integer> {
private static final long serialVersionUID = 1L;
@Basic(optional = false)
@Column(nullable = false, length = 125)
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(joinColumns = {
@JoinColumn}, inverseJoinColumns = {
@JoinColumn(name = "instrument_traded_id")}, uniqueConstraints =
@UniqueConstraint(name = "UK_client_instruments_traded_client_id_instrument_traded_id",
columnNames = {"client_id", "instrument_traded_id"}))
@ForeignKey(name = "FK_client_instruments_traded_client_id",
inverseName = "FK_client_instruments_traded_instrument_traded_id")
private List<InstrumentTraded> instrumentsTraded;
public Client() {
}
public List<InstrumentTraded> getInstrumentsTraded() {
return instrumentsTraded;
}
public void setInstrumentsTraded(List<InstrumentTraded> instrumentsTraded) {
this.instrumentsTraded = instrumentsTraded;
}
...
}
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(name = "UK_instrument_traded_name", columnNames = {"name"})})
public class InstrumentTraded extends AbstractEntity<Integer> {
private static final long serialVersionUID = 1L;
@Basic(optional = false)
@Column(nullable = false, length = 50)
private String name;
@ManyToMany(mappedBy = "instrumentsTraded", fetch = FetchType.LAZY)
private List<Client> clients;
public InstrumentTraded() {
}
public List<Client> getClients() {
return clients;
}
public void setClients(List<Client> clients) {
this.clients = clients;
}
...
}
做一些後研究它看起來像唯一的解決方案是mapping a join table with additional columns使用@OneToMany
@IdClass
和複合主鍵類,當我不需要額外的列。除了上面代碼中包含的解決方案之外,這是唯一的解決方案,它使用@UniqueConstraint
以及@ManyToMany
映射中的兩個外鍵列?對於像這樣的常見場景所需的工作量似乎有點荒謬。謝謝!
http://stackoverflow.com/questions/1212058/how-to-make-a-composite-primary-key-java-persistence-annotation/6344626#6344626 – steveeen 2011-06-14 14:14:39
還值得檢查,如果你意外地沒有添加一個記錄兩次,這發生在我身上,所以'list.add(x); list.add(x);'結果在列表中重複。 – CsBalazsHungary 2014-10-30 15:58:57