Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Saturday

JPA (Java Persistence API) Tutorial ElementCollection – how to map a list of values into a class

ElementCollection – how to map a list of values into a class

Sometimes it is needed to map a list of values to an entity but those values are not entities themselves, e.g. person
has emails, dog has nicknames etc.
Check the code below that demonstrates this situation:

import java.util.List;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue

private int id;

private String name;
@ElementCollection
@CollectionTable(name = "person_has_emails")
private Set<String> emails;
@ElementCollection(targetClass = CarBrands.class)
@Enumerated(EnumType.STRING)
private List<CarBrands> brands;
// get and set
}
public enum CarBrands {
FORD, FIAT, SUZUKI
}
About the code above:
•Notice that two lists of data are used: Set<String>, List<CarBrand>. The @ElementCollection
annotation is used not with entities but with “simple” attributes (e.g. String, Enum etc).
•The @ElementCollection annotatio is used to allow an attribute to repeat itself several times.
•The @Enumerated(EnumType.STRING) annotation is used with the @ElementCollection
annotation. It defines how the enum will be persisted in the database, as String or as Ordinal
(click here to more information).
•@CollectionTable(name = “person_has_emails”) => configure JPA to which table the information
will be stored. When this annotation is not present JPA will create a database table named after
the class and attribute name by default. For example with the “List<CarBrand> brands”

attribute the database table would be named as "person_brands".

NEXT

No comments:

Post a Comment