Songo
Songo

Reputation: 5736

How to model a User having multiple Addresses?

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:

  1. Create 2 different collections for work addresses and personal addresses then map them into 2 different tables. ( Sounds like over complicating things as both addresses are exactly the same)
  2. Store both addresses into the same table. (However, I don't know how will I differentiate between them)
  3. Introduce a look up entity/value object and use it somehow to differentiate between personal and work addresses. (from the database point of view we will have a look up table for address types linked via a foreign key to the address table, but I don't know how that should be modeled in the domain itself using Hibernate)

Alternative approaches are very welcomed.

Upvotes: 0

Views: 1240

Answers (1)

Angular University
Angular University

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

Related Questions