2

I think it is possible (in general) to have a unique constraint on a table columns, but only those that are not null (e.g. I read here https://stackoverflow.com/a/767702/3733425)

But is it possible in hibernate?

Here I have an entity with 3 fields (a,b,c) that together should be unique.

But if a is null (which is very common), then the constraint should not apply

In other words, there can be many (0, b, c) rows, but only unique (a != 0, b , c)

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"a", "b", "c"}))
public class Widget {
    @Id
    @GeneratedValue;
    private Long id;

    @Basic(optional = true)
    private Integer a;

    @Basic(optional = false)
    private String b;

    @Basic(optional = false)
    private Long c;

    ...
}
Community
  • 1
  • 1
Merchuk Hul
  • 245
  • 1
  • 2
  • 11

0 Answers0