@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "overoptimisation_identifiers")
public class OveroptimisationIdentifierEntity {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", columnDefinition = "VARCHAR(255)")
private UUID id;
@CreationTimestamp
private LocalDate date;
}
I'd like to have only one identifier per day. This means that I have to organise a constraint: id and date are unique together.
By the way, maybe it is not done by JPA. It may be done by the framework, a third party library or just by me in the code. But I don't know how to do that.
CodePudding user response:
It sounds like you want to create a unique constraint on the id and date columns of the overoptimisation_identifiers table. In JPA, you can do this by using the @Table annotation and specifying a uniqueConstraints attribute.
Here is an example of how you could modify your OveroptimisationIdentifierEntity class to add a unique constraint on the id and date columns:
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "overoptimisation_identifiers", uniqueConstraints = {
@UniqueConstraint(columnNames = {"id", "date"})
})
public class OveroptimisationIdentifierEntity {
// ...
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", columnDefinition = "VARCHAR(255)")
private UUID id;
@CreationTimestamp
private LocalDate date;
}
This will tell JPA to create a unique constraint on the id and date columns when generating the table schema. This will prevent multiple rows with the same values for the id and date columns from being inserted into the table.