gpt4 book ai didi

java - JPA如何通过只读取外键值来建立JoinTable关系

转载 作者:太空宇宙 更新时间:2023-11-04 14:19:28 24 4
gpt4 key购买 nike

我有一个实体 A 和枚举常量 B。我没有为枚举类定义实体。但有一张 table 为其定义的。我有一个连接表,用于存储属于 A 实体的 B 枚举。

在实体 A 中,我必须定义这种关系。我想读取枚举类的整数值。通常我们通过以下方式定义这种关系。

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "A_ENUMS", joinColumns = @JoinColumn(name = "A_ID", referencedColumnName = "ID", updatable = false),
inverseJoinColumns = @JoinColumn(name = "ENUM_ID", referencedColumnName = "ID", updatable = false))
private Collection<Integer> enums;

我尝试过这个,但没有成功。因为我加载的是整数,而不是实体。我如何通过 JPA 执行此操作?

最佳答案

// + No need for [Cascade.ALL],
// + @ElementCollection will be cascaded by default like any A's @Column
@ElementCollection(fetch = FetchType.EAGER)
// + You can omit @CollectionTable if you want as all the values you've used,
// are the JPA default values (I assume that [ID] is @Id of the table [A] )
// + No need for inverseJoinColumns, and you should not use [ID]
// for Enum as it's not an entity, and you're interesetd in the integer value instead
// + updatable = false is ommited, it doens't not make much sense here.
@CollectionTable(name = "A_ENUMS",
joinColumns = @JoinColumn(name = "A_ID", referencedColumnName = "ID"))
// + Replace [MyIntegerEnum] with the column name of enum value used in [A_ENUMS] table
@Column(name = "MyIntegerEnum")
private Collection<Integer> enums;

@ElementCollection

@OneToMany vs @ElementCollection

关于java - JPA如何通过只读取外键值来建立JoinTable关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27354948/

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