如何在@ElementCollection上指定主键

问题描述 投票:0回答:4

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

因此,在 Hibernate 中,我正在寻找一个键来指定 @ElementCollection 表上的主键,并以 Set 作为底层数据结构。

我找到了一种带有地图的主键的方法,但这有点奇怪,因为我不需要地图。

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

知道如何实现这一目标吗?

java hibernate jpa orm hibernate-mapping
4个回答
18
投票

如果你使用Set并且使元素Column不为空,那么hibernate将使用连接列和元素列创建主键。

示例:

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

4
投票

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

您可以添加

@OrderColumn
来优化生成的SQL语句。

如果您需要主键,那么您应该将

@ElementCollection
转换为
@OneToMany
关联。


0
投票

在 Spring Boot / Data JPA 2.5.2、hibernate-core 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 表:

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`)
)

0
投票

这个例子来自一本《java persistence with spring data and hibernate》一书, 不适用于 Set,但适用于 java.util.Collection.Collection 或 List

@org.hibernate.annotations.GenericGenerator(名称=“sequence_gen”,策略=“序列”) @org.hibernate.annotations.CollectionId(column = @Column(name = "NAME_ID"), type = @Type( type = "long"), Generator = "sequence_gen" ) @CollectionTable(schema = "", name = "NAMES", joinColumns = @JoinColumn(name = "ROOT_ID")) @ElementCollection 私有列表名称 = new ArrayList<>();

© www.soinside.com 2019 - 2024. All rights reserved.