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

时间:2014-12-08 09:27:53

标签: java hibernate jpa

我有一个实体A和枚举常量B.我没有为枚举类定义一个实体。但是有一张桌子 为它定义。我有一个连接表,存储属于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做到这一点?

1 个答案:

答案 0 :(得分:0)

// + 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