spring-bootjpaspring-data-jpaspring-boot-jpa

cause.getConstraintName() returning a weird string instead of actual constraint name


I have a column set to as unique = true.

Here is the code of my entity -

@Entity
@Table(name = "users", uniqueConstraints=[UniqueConstraint(name = "userName", columnNames=["user_name"])])
class UserEntity(@Column(name = "user_id", nullable = false)
                 @Id @GeneratedValue(strategy = GenerationType.AUTO)
                 var id: Long = 0,
                 @Column(name = "user_name", nullable = false, unique = true)
                 @field:NotEmpty(message = "Please provide a user name")
                 var userName: String?)

Now when there is a DataIntegrityViolationException or ConstraintViolationException due to attempt to insert a duplicate user_name I try to extract the exact name of constraint name like this -

val failConstraint = (ex.cause as ConstraintViolationException).constraintName

However, instead of proper constraint name, I get a weird string - "uk_k8s0f4n7n77w1a16yhua69ony"

The detailed message is this -

ERROR: duplicate key value violates unique constraint "uk_k8s0f4n7n77w1a16yhua69ony"\n Detail: Key (user_name)=(krtkush) already exists.

I'm roughly following this answer - Identify constraint name that trigger DataIntegrityViolationException

Where am I going wrong?


Solution

  • I had to invalidate my IDE's cache and restart it for it to work. Nothing wrong with the code.