簡體   English   中英

有沒有辦法使單個 JPA 實體中的兩個外鍵組合唯一?

[英]Is there a way to make the combination of two foreign keys in a single JPA entity unique?

我有兩個實體,分別稱為 A 和 B。有一個關系實體 C 支持 A 和 B 之間的多對多關系。C 具有 A 的外鍵和 B 的外鍵,都標有 @ManyToOne 和@JoinColumn 注釋。

我的用戶希望系統強制為給定的 A 和 B 創建一個 C 記錄,所以我想聲明 A 外鍵和 B 外鍵的組合必須是唯一的。

我嘗試在 C 表上使用以下注釋,但出現錯誤,列出的外鍵不存在。

@Table(uniqueConstraints=@UniqueConstraint(name = "UIDX_a_b", columnNames = {"aId, bId"}))
@Entity
@Table(uniqueConstraints=@UniqueConstraint(name = "UIDX_a_b", columnNames = {"aId, bId"}))
public class C{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    @ManyToOne(optional=false)
    @JoinColumn(name="aId")
    private A a;
    @ManyToOne(optional=false)
    @JoinColumn(name="bId")
    private B b;
        ...

當我嘗試 @Table 注釋時,我收到以下錯誤:

Caused by: org.hibernate.AnnotationException: Unable to create unique key constraint (aId, bId) on table C: database column 'aId, bId' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)

columnNames = {"aId, bId"}應該是columnNames = {"aId","bId"}

或者,如果這不能產生您正在尋找的結構,也許這個變體

@Table(indexes = { @Index(name = "UIDX_a_b",  columnList="aId,bId", unique = true) })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM