2

I'm confused about when to use one over the other, or both together.

From the answers to this question, I get that @ElementCollection is used when we want to map a non-entity. But then there seems to be cases when both are used at the same time, as here,

  @ElementCollection(targetClass=Role.class)
  @JoinTable(name = "USER_ROLES", joinColumns = @JoinColumn(name = "USER_ID"))
  @Enumerated(EnumType.STRING)
  @Column(name = "role", nullable = false)
  public Set<Role> getRoles() {
    return roles;
  }

or here,

@ElementCollection(targetClass = Days.class)
@CollectionTable(name = "days", joinColumns = @JoinColumn(name = "rule_id"))
@Column(name = "daysOfWeek", nullable = false)
@Enumerated(EnumType.STRING)
public Set<Days> getDays() {
    return days;
}

But then, I don't really understand when they shouldn't go together. I guess, but I'm not sure, that the question is whether my enum is an entity or not, as said in this answer.

You should decide whether your Platform is an entity or not.

So my questions are:

  1. Do @ElementCollection and @Enumerated overlap in any way or are completely independent? If independent, I decide if my entity is mapped, and then if it happens to be an enum. Correct?

  2. How do I decide if I want my enum to be an entity? An example would be highly appreciated.

Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82
user3748908
  • 885
  • 2
  • 9
  • 26
  • 1
    CollectionTable is for non-Entity elements.. The first one (JoinTable) is inappropriate for non-entities. An Enum is not an Entity, ever! – Neil Stockton Dec 14 '15 at 10:21
  • @NeilStockton: So `ElementCollection` and `JoinTable` shouldn't ever appear together? Why doesn't hibernate complain about it? – user3748908 Dec 14 '15 at 10:37
  • maybe because it ignores JoinTable? who knows. Ask a Hibernate developer. The JPA spec is very clear – Neil Stockton Dec 14 '15 at 11:14

0 Answers0