How to introduce multi-column constraint with JPA annotations?

You can declare unique constraints using the @Table(uniqueConstraints = ...) annotation in your entity class, i.e.

@Entity
@Table(uniqueConstraints={
    @UniqueConstraint(columnNames = {"productId", "serial"})
}) 
public class InventoryItem {
    ...
}

Note that this does not magically create the unique constraint in the database, you still need a DDL for it to be created. But seems like you are using some sort of automated tool for creating the database based on JPA entity definitions.

Leave a Comment