【问题标题】:JPA/Hibernate - Use unique constraint as primary keyJPA/Hibernate - 使用唯一约束作为主键
【发布时间】:2016-06-16 16:23:02
【问题描述】:

我有以下问题,我有一个已经存在的表,其中包含三个字段 field1、field2、field3。 Field1 实际上是另一个表的外键 (@OneToOne)。所有 field2 和 field3 都可以为 null,因此我无法为所有三个字段设置主键。在数据库中有 field1+field2+field3 的 UniqueConstraint。

field1 | field2 | field 3
 1     |   1    |   null
 1     |  null  |   2
 3     |   1    |   null

我已经尝试了几种使用 JPA/Hibernate 的解决方案,但找不到一个好的解决方案。 如果不定义 @Id,JPA 将无法工作(当然)。在 @Embeddable 中定义三个字段并通过 @EmbeddedId 重用它会在所有三个不允许空值的字段上创建一个主键。

除了更改现有表并为每一行添加自动生成的 id 之外,还有其他解决方案吗?

非常感谢您的问候!

【问题讨论】:

  • Field2、Field3是干什么用的?它们是另一张桌子上的钥匙吗?请注意,Field1 与父表具有 ManyToOne 关系,其中 id 1 存在两次。

标签: java hibernate jpa uniqueidentifier identifier


【解决方案1】:

您尝试过以下方法吗?

@Table(
    name="xxx", 
    uniqueConstraints=
        @UniqueConstraint(name="my_unique_key", columnNames={"field1", "field2", "field3"})
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多