I have some existing project and used both unique =true at column level and @UniqueConstraints at entity class level for the same column as below. I am currently doing code refactor so need suggestion to improve the code.
@Table(name = "sales_order", uniqueConstraints = @UniqueConstraint(columnNames = "order_no"))
public class SalesOrder implements java.io.Serializable {
private static final long serialVersionUID = 6008509031685325038L;
//primary key column with some other columns
@Column(name = "order_no", unique = true, nullable = false)
private String orderNo;
}
We can not use both for the same unique column right ? In the above code, which one is the best to use or define unique constraint? I would say if it's single column unique then can use unique=true at column level and if unique key contains multiple columns then use @UniqueConstraints.
"Best" is obviously subjective, but your proposed approach works well. And it describes the only limitation, forcing the use of one over the other.
I would say if it's single column unique then can use
unique=true
at column level and if unique key contains multiple columns then use@UniqueConstraints
.
Of course, one might argue for always using @UniqueConstraints
in order to make the code more uniform.
But that is really a matter of code style.