Map collections of primitives
Sometimes, you need to associate your entity with a collection of primitive values to represent a simple one/many-to-many relationship. For example, each movie has a set of associated genres that we want to keep stored in the database. To represent them from an object-oriented perspective, we will define a list (collection) of strings in our Movie
class. To reflect this relationship inside the database, we will use the @ElementCollecion
annotation, as shown in the following example:
@Entity public class Movie { @Id @GeneratedValue private long id; private String title; @ElementCollection private List<String> genres = new ArrayList<>(); public Movie() { } // getters and setters here }
The @ElementCollection
annotation will make the JPA provider create another table (movie_genres
) to store the list of genres, mapped to the movies table using the movie's primary key as a secondary key in the (movie_genres...