Sobes.tech
Senior

Tell me about the @ElementCollection annotation.

sobes.tech AI

Answer from AI

The @ElementCollection annotation in Java Persistence API (JPA) is used to map collections of basic or embeddable types that are not entities themselves. It allows storing a collection of values (e.g., a list of strings or embedded objects) in a separate table associated with the main entity.

Example usage:

@Entity
public class User {
    @Id
    private Long id;

    @ElementCollection
    @CollectionTable(name = "user_emails", joinColumns = @JoinColumn(name = "user_id"))
    @Column(name = "email")
    private Set<String> emails = new HashSet<>();

    // getters and setters
}

In this example, the User entity has a collection of email addresses stored in a separate table user_emails. The @ElementCollection indicates that this is not a separate entity but a collection of embedded elements.