1

I have an entity A and enum constant B. I did not define an entity for enum class. But there is a table defined for it. I have a join table that stores B enums belonging A entity.

In the entity A , I have to define this relationship. 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?

user725455
  • 465
  • 10
  • 36
  • `@OneToMany` is for relation between entities, try using `@ElementCollection` instead as [enums] doesn't represent concrete entity! – O.Badr Apr 06 '17 at 09:47

1 Answers1

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

O.Badr
  • 2,853
  • 2
  • 27
  • 36