I have a Product entity and it's name and category combination should be unique for every product.
In my case name is required, but category may not be present.
Product is defined like this:
@Entity
@Table(
    uniqueConstraints=
        @UniqueConstraint(columnNames={"name", "category")
)
public class Product {
    // ...
    @NotNull
    @Size(min = 1, max = 64)
    private String name;
    @ManyToOne(fetch = FetchType.EAGER)
    private ProductCategory category;
    // ...
}
... but the constraint works only when category is not NULL.
In other words I cannot persist (and this is ok) entities with:
name="example", category=1
name="example", category=1
... at the same time I can persist (and this is not what I want) entities wihh:
name="example", category=null
name="example", category=null
So, my question is - how do I implement unique constraint for combination of fields, one of which can be nullable (with NULL treated as any other value)?
PS: I use Hibernate as JPA provider and MySQL database.
 
    