2014-12-08 46 views
1

我有一个实体A和枚举常量B.我没有为枚举类定义一个实体。但是有一个为其定义的表 。我有一个连接表,用于存储属于实体的B枚举。JPA如何通过只读外键值设置JoinTable关系

在实体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做到这一点?

+0

'@ OneToMany'是实体之间的关系,尝试使用'@ ElementCollection'不是作为[枚举],并不代表具体的实体! – 2017-04-06 09:47:55

回答

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

+0

这是一个迟到的答案,但它可能有助于这个星球上的人,甚至在这个星系! – 2017-04-11 08:07:32