Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate two column unique index cannot update values

So I am trying to add a unique constraint that uses two column. I added the unique constraint in db and I have following Java code

@Entity
@Table(
    name = "test_table",
    uniqueConstraints = @UniqueConstraint(
        columnNames = {
            "other_table_id",
            "sort_order"
        },
        name = "my_unique_constraint")
)
class SomeTable {

    private String label;

    @ManyToOne(optional = false)
    @JoinColumn(name = "other_table_id", nullable = false)
    private OtherTable otherTable;

    @NotNull
    @Column(name = "sort_order", nullable = false)
    private int sortOrder;
}

When I modify the sorting for this table and update the record I get

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
 Duplicate entry '1-2' for key 'my_unique_constraint'

How do I implement @UniqueConstraint such that I don't get this kind of error.

like image 594
A0__oN Avatar asked Jan 30 '26 20:01

A0__oN


1 Answers

You get this error because your uniqueConstraints aren't separated.

So my approach is to separate the two constraints:

@Table(
    name = "test_table",
    uniqueConstraints = {
            @UniqueConstraint(columnNames = "other_table_id"),
            @UniqueConstraint(columnNames = "sort_order")
    },
        name = "my_unique_constraint")
)
like image 179
Atimene Nazim Avatar answered Feb 01 '26 10:02

Atimene Nazim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!