gpt4 book ai didi

java - JPA OneToMany-Mapping 没有多边映射类

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:18 27 4
gpt4 key购买 nike

在使用 JPA 2.1 和 Hibernate 的 Spring Boot 应用程序中,有两个感兴趣的 (PostgreSQL) 表:

entity                                external_id--                                    --id serial                             id serial...                                   entity_id int...                                   external_id int

The relation between entity and external_ids is obviously OneToMany, which I want to use in the JPA mapping as well. A simple way to do this is to create @Entity-mappings for each table and use a @OneToMany-relation:


@Entity
public class Entity {
@Id
private Integer id;

@OneToMany(mappedBy= "entityId")
private Set<ExternalId> externalIds;
}

@Entity
public class ExternalId {
@Id
private Integer id;

@ManyToOne
private Integer entityId;

private Integer externalId;
}

但由于表 external_ids 只包含每个实体成员的数字列表,我想在没有表 external_id 的显式映射的情况下立即映射 external_id.external_id 的值:


@Entity
public class Entity {
@Id
private Integer id;

@OneToMany(???)
private Set<Integer> externalIds;
}

这对于 JPA 2.1 是否可行?如果可行,如何实现?

最佳答案

您可以利用 @ElementCollection为此目的:

@ElementCollection
@CollectionTable(name = "TableName", joinColumns=@JoinColumn(name = "JoinColumnName"))
private Set<Integer> externalIds;

关于java - JPA OneToMany-Mapping 没有多边映射类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32630028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com