I created a table that had a unique constraint of user_id
, document_id
and status
:
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "user_id", "document_id",
"status" }), name = "acquired_document")
@EntityListeners(AuditingEntityListener.class)
public class AcquiredDocument {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long acquiredDocumentId;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false, updatable = false)
private User user;
@Column(name = "document_id", nullable = false, updatable = false)
private String documentId;
@Column(name = "status", nullable = false)
private String status;
Now due to change in requirements we need to have a unique constraint disable on these three columns if the status is "FAILED" (to enable multiple failed documents to be acquired).
So this is invalid:
+-----+----------+-------------+--------+
| id | user_id | document_id | status |
+-----+----------+-------------+--------+
| 1 | 1 | 1 | PAID |
| 2 | 1 | 1 | PAID |
+-----+----------+-------------+--------+
But this should not be:
+-----+----------+-------------+--------+
| id | user_id | document_id | status |
+-----+----------+-------------+--------+
| 1 | 1 | 1 | FAILED |
| 2 | 1 | 1 | FAILED |
+-----+----------+-------------+--------+
I am using JPA (JAVA 1.8) and mySQL server 5.7.