【问题标题】:Hibernate generates wrong primary keyHibernate 生成错误的主键
【发布时间】:2020-11-05 15:15:36
【问题描述】:

我有一个 Hibernate 实体。

@AllArgsConstructor @NoArgsConstructor @Getter
@Entity
@Table(name = "app_category_link", schema = "mariott_application")
public class AppCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "app_category_link_id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "app_id")
    private App app;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id")
    private Category category;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id_who_added")
    private User userWhoAdded;

    @Column(name = "date_add")
    private ZonedDateTime dateAdded;
}

我有一个@DataJpaTest 生成了这样的 DDL。令人惊讶的是,它产生了一个意想不到的主键。

create table mariott_application.app_category_link
(
    app_category_link_id int8      not null,
    date_add             timestamp,
    app_id               bigserial not null,
    category_id          int8      not null,
    user_id_who_added    int8,
    primary key (app_id, category_id)     -- wrong
)

为什么Hibernate会生成错误的主键?

【问题讨论】:

  • 您是否也可以将此表名用于其他映射?除此之外,您使用的是哪个版本?
  • 这个表名是唯一的。我使用 Hibernate 5.4.18.Final 和 Spring Boot 2.3.2.RELEASE
  • 你能调试到org.hibernate.mapping.Table#setPrimaryKey看看为什么会这样设置吗?
  • 我想我找到了问题所在。我在AppCategory 之间有ManyToMany 关系。链接AppCategory#appAppCategory#category 是无方向的。我认为这就是为什么 Hibernate 在第二遍中用 (app_id, category_id) 覆盖主键

标签: java spring-boot hibernate spring-data-jpa spring-test


【解决方案1】:

当您多次使用表名时可能会发生这种情况,例如也在@JoinTable/@CollectionTable。始终将现有实体用作反向 @OneToMany 而不是定义 @ManyToMany 关联以避免此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多