1

Let's assume I do have an Offer entity. It has a property salaries that may be a list of Salary objects. The Salary cannot exist without an Offer, so does it mean I should use @ElementCollection or may not? When should we use @ElementCollection and when @OneToMany. The same question comes to my mind when we talk about @Embeddable and @Embedded, is it worth using it, or perhaps it's better to have a @OneToOne relationship.

class Salary(
    val salary_from: Integer,
    val salary_to: Integer,
    val salary_type: Type
)

class Offer(
    @ElementCollection
    @CollectionTable(name = "offer_salaries", joinColumns = @JoinColumn(name = "offer_id"))
    @OrderColumn
    @Column(name = "salaries")
    val salaries: List<Salary>;
)
Reddi
  • 677
  • 6
  • 19
  • ElementCollection is highly inefficient. – Alien Dec 02 '21 at 12:55
  • @Alien Why? Can you provide more details? Does it mean that `@Embeddable` and `@Embedded` are also inefficient and it's better to use `@OneToOne`? – Reddi Dec 02 '21 at 13:04

1 Answers1

-1

@OneToMany is meant for when you want to map to a db table as an entity. @ElementCollection: you can look at it as a regular collection which is used for mapping non-entities.

ref: Difference between @OneToMany and @ElementCollection?

E.G: you have a Perfume entity and it has 2 lists.

  • scents - is a list of attribues (should be @ElementCollection) since it contains some attributes which are not entities.
  • customers - is a list of entities (should be @oneToMany since it should be mapped as an entity)