【发布时间】: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 Boot2.3.2.RELEASE -
你能调试到
org.hibernate.mapping.Table#setPrimaryKey看看为什么会这样设置吗? -
我想我找到了问题所在。我在
App和Category之间有ManyToMany关系。链接AppCategory#app和AppCategory#category是无方向的。我认为这就是为什么 Hibernate 在第二遍中用(app_id, category_id)覆盖主键
标签: java spring-boot hibernate spring-data-jpa spring-test