【问题标题】:cause.getConstraintName() returning a weird string instead of actual constraint namecause.getConstraintName() 返回一个奇怪的字符串而不是实际的约束名称
【发布时间】:2020-07-31 14:19:57
【问题描述】:

我有一列设置为unique = true

这是我的实体的代码 -

@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?)

现在,当由于尝试插入重复的 user_name 而出现 DataIntegrityViolationExceptionConstraintViolationException 时,我尝试像这样提取约束名称的确切名称 -

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

但是,我得到一个奇怪的字符串,而不是正确的约束名称 - “uk_k8s0f4n7n77w1a16yhua69ony”

详细的留言是这里-

错误:重复键值违反唯一约束 "uk_k8s0f4n7n77w1a16yhua69ony"\n 详细信息:密钥 (user_name)=(krtkush) 已经存在了。

我大致遵循这个答案 - Identify constraint name that trigger DataIntegrityViolationException

我哪里出错了?

【问题讨论】:

  • 添加uniqueConstraints=[UniqueConstraint 后,您是否删除了数据库并通过休眠重新创建了表?否则旧的约束名称将在那里
  • 我做到了。但我是通过我正在使用的 GUI 工具而不是通过休眠完成的。
  • 原来我需要使缓存无效并重新启动我的 IDE。

标签: spring-boot jpa spring-data-jpa spring-boot-jpa


【解决方案1】:

我必须使我的 IDE 缓存无效并重新启动它才能工作。代码没有错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 2023-04-05
    相关资源
    最近更新 更多