Embeddable classes
An entity may use other fine-grained classes to represent entity state. Instances of these classes, unlike
entity instances, do not have persistent identity of their own. Instead, they exist only as part of the state
of the entity to which they belong.
In short, an embeddable is ...
Examples
\< IMAGE \\\>
Collections of Embeddables
In the code snippet below, there is a User2 Entity which has a collection of ordered Embedded address.
@Embeddable public class Address { @Basic private String street; @Basic private String city; @Basic private String state; @Basic private Integer zip; public Address(){ } //... }
@Entity public class User2 { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @ElementCollection @CollectionTable(name="user_addresses") @OrderColumn private Set<Address> addresses = new HashSet<Address>(); public User2(){ } //... }
Relationships from Embeddables
In the code snippet below, there is an Address embeddable with a ManyToOne relationship to a Coordinates Entity.
@Embeddable public class Address { @Basic private String street; @Basic private String city; @Basic private String state; @Basic private Integer zip; @ManyToOne(cascade=CascadeType.ALL) Coordinates coordinates; public Address(){ } //... }
@Entity public class Coordinates { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) int id; @Basic double longitude; @Basic double latitude; public Coordinates(){ } public Coordinates(double lon, double lat){ longitude=lon; latitude=lat; } //... }
Nested Embeddables
In the code snippet below, there is a User Entity which has an embedded ContactInfo. ContactInfo contains two other embeddeded embeddables, Address and Phone.
@Embeddable public class Address { @Basic private String street; @Basic private String city; @Basic private String state; @Basic private Integer zip; public Address(){ } //... }
@Embeddable public class Phone { @Basic private String number; //... }
@Embeddable public class ContactInfo { public ContactInfo(){ } @Embedded Address homeAddress; @Embedded Phone homePhone; //... }
@Entity public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Embedded ContactInfo contactInfo; public User(){ } //... }