如何在@ElementCollection 上指定主键

How to specify a Primary Key on @ElementCollection

因此,如果某些 table 缺少主键,innodb 的行为可能会导致问题。

所以对于 Hibernate,我正在寻找一个键来指定 @ElementCollection table 上的主键,并将 Set 作为底层数据结构。

我找到了一种通过映射获得主键的方法,但这有点奇怪,因为我不需要映射。

我也找到了一个与@Embeddable 相关的答案,但我不需要那么复杂。我在我的实体中使用 Set 或 Set 作为数据结构。

知道如何实现吗?

@ElementCollection 不能使用主键,因为 Embeddable 类型不能有标识符。

您可以 add an @OrderColumn 优化生成 SQL 语句。

如果你需要一个主键,那么你应该把 @ElementCollection 变成一个 @OneToMany 关联。

如果您使用 Set 并使元素 Column 不为空,则 hibernate 将使用连接列和元素列创建一个主键。

示例:

@Column(name = "STRINGS", nullable = false)
@ElementCollection
private Set<String> strings;

在 Spring 引导/数据 JPA 2.5.2、休眠核心 5.4.32 上测试:

@Entity
@Table(name = "user")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Data
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ElementCollection(fetch = FetchType.EAGER, targetClass = Role.class)
    @Enumerated(EnumType.STRING)
    @CollectionTable(
        name = "user_role",
        joinColumns = @JoinColumn(name = "user_id")
    )
    @Column(name = "role", nullable = false)
    private Set<Role> roles; // public enum Role {ADMIN,USER}
}

产生 MySQL table:

CREATE TABLE `user_role` (
  `user_id` bigint(20) NOT NULL,
  `role` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`user_id`,`role`),
  CONSTRAINT `FK_random_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
)