简体   繁体   English

JPA如何通过只读取外键值来设置JoinTable关系

[英]JPA how to set up JoinTable relationship by reading only foreign key value

I have an entity A and enum constant B. I did not define an entity for enum class.我有一个实体 A 和枚举常量 B。我没有为枚举类定义实体。 But there is a table defined for it.但是有一个为它定义的表。 I have a join table that stores B enums belonging A entity.我有一个连接表,用于存储属于 A 实体的 B 枚举。

In the entity A , I have to define this relationship.在实体 A 中,我必须定义这种关系。 I want to read integer values for enum class.我想读取枚举类的整数值。 In normally we define this kind of relationship in following way.通常,我们通过以下方式定义这种关系。

@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;

I tried this, but it did not work.我试过这个,但没有用。 Because I am loading integer, not entity.因为我正在加载整数,而不是实体。 How can I do this via JPA?我怎样才能通过 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 @OneToMany@ElementCollection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM