Reputation: 5736
I have a User entity. Each User can have one or more personal Addresses. According to the Hibernate documentation for mapping embeddable collections this is how it should be done:
@Entity
public class User {
[...]
public String getLastname() { ...}
@ElementCollection
@CollectionTable(name="Addresses", joinColumns=@JoinColumn(name="user_id"))
@AttributeOverrides({
@AttributeOverride(name="street1", column=@Column(name="fld_street"))
})
public Set<Address> getAddresses() { ... }
}
@Embeddable
public class Address {
public String getStreet1() {...}
[...]
}
Now if I want the User to have a collection for work addresses too, what should I do?
Here is what I thought:
Alternative approaches are very welcomed.
Upvotes: 0
Views: 1240
Reputation: 43087
Try using hibernate single table inheritance mapping:
@Entity
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="addresstype",
discriminatorType= DiscriminatorType.STRING)
public abstract class Address {
... common attributes here
}
@Entity
@DiscriminatorValue("home")
public class HomeAddress extends Address {
...
}
@Entity
@DiscriminatorValue("work")
public class WorkAddress extends Address {
...
}
And then create two collections, one for home addresses and the other for work addresses.
If there is code that is valid only for home addresses then we use the HomeAddress type, the same if there is code that is only valid for work addresses we use WorkAddress.
If there is code that is valid for both address types then we use the Address super type.
Upvotes: 1