The easiest way to pin point the cause of constraint violation, is to define the name of the constraint properly in the first place:
Defining Unique Constraint:
Using @UniqueConstraint
inside @Table
, we can either define one column or multiple columns constraints, along with a custom constraint name:
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "name" }, name = "name_constraint"),
@UniqueConstraint(columnNames = { "teamId", "orderIndex" }, name = "teamId_orderIndex_constraint")
})
public class Space {
// .. other field omitted
private String name;
private Integer orderIndex;
private Integer teamId;
}
JPA alter the constraint with our custom name:
Hibernate:
alter table space
add constraint name_constraint unique (name)
Hibernate:
alter table space
add constraint teamId_orderIndex_constraint unique (team_id, order_index)
Properly handle DataIntegrityViolationException
:
Using e.getMessage()
, we get result back, which contains the name of the constraint we defined above:
could not execute statement; SQL [n/a]; constraint [space.name_constraint]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
Then simply check if the result contains the name we defined:
import org.springframework.dao.DataIntegrityViolationException;
try {
repository.save(space);
} catch (DataIntegrityViolationException e) {
if(e.getMessage().contains("name_constraint")) {
System.out.println("Unique name constraint violated");
}
if(e.getMessage().contains("teamId_orderIndex_constraint")) {
System.out.println("Unique teamId_orderIndex constraints violated");
}
}
Reference: Defining Unique Constraints in JPA