[英]Modifying Annotations to avoid `unique constraint or index violation` error?
[英]Conditional unique constraint using annotations
我有兩個相關的實體有兩種不同的類型(GENERAL和CUSTOM),我把它保存在同一個表中。 類型為GENERAL的實體應具有唯一的字段名稱值,並且CUSTOM可以為不同的用戶提供重復項,而不是重復的GENERAL名稱。 我正在尋找一種方法來創建條件唯一約束,以檢查下一個案例:
如果實體具有類型CUSTOM,則名稱可以在表中重復但不能復制GENERAL項,並且對於特定用戶應該是唯一的(按用戶ID)
@Entity @Table(name = "Purpose", uniqueConstraints = @UniqueConstraint(columnNames = {"purposeId"})) @Inheritance(strategy=InheritanceType.SINGLE_TABLE) public class GeneralPurpose {
\n\n
@Id @GeneratedValue(strategy = GenerationType.AUTO,generator =“purpose_seq_gen”)@SequenceGenerator(name =“purpose_seq_gen”,sequenceName =“PURPOSE_SEQ”)@Column(name =“purposeId”,nullable = false)private long purposeId;
\n\n@Column(name =“type”,nullable = false)@Enumerated(EnumType.STRING)private PurposeType類型;
\n\n@Column(name =“name”,nullable = false)私有字符串名稱;
@Entity @Table(name = "Purpose") public class CustomPurpose extends GeneralPurpose {
\n\n
@ManyToOne()@ JoinColumn(name =“id”)@JsonIgnore私人用戶用戶;
public enum PurposeType { GENERAL, CUSTOM }
您可以通過向“目的”表添加另一列來完成此操作。 此列用於存儲GENERAL記錄的常量值和CUSTOM記錄的用戶ID。 對於GENERAL記錄,值可以是0(如果用戶標識是數字)或“GENERAL”(如果用戶標識是字符串)。 它可以命名為'userOfRecord'或'recordDiscriminator',就像那樣。
然后,您可以在[type,name,userOfRecord]上添加唯一約束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.