Collections Embeddables
In the code snippet below, there is a User2 Entity which has a collection of ordered Embedded address.
Address.java
@Embeddable public class Address { @Basic private String street; @Basic private String city; @Basic private String state; @Basic private Integer zip; public Address(){ } //... }
User2.java
@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.
Address.java
@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(){ } //... }
Coordinates .java
@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.
Address.java
@Embeddable public class Address { @Basic private String street; @Basic private String city; @Basic private String state; @Basic private Integer zip; public Address(){ } //... }
Phone.java
@Embeddable public class Phone { @Basic private String number; //... }
ContactInfo.java
@Embeddable public class ContactInfo { public ContactInfo(){ } @Embedded Address homeAddress; @Embedded Phone homePhone; //... }
User.java
@Entity public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Embedded ContactInfo contactInfo; public User(){ } //... }