3

I'm new to hibernate. I'm trying to store a person with one type of address (either domestic or international address). I understand my example below may seem a bad design for some people. Let's assume that's the requirement.

I'm able to store one type of address using @Embedded, but I had to state DomesticAddress or InternationalAddress, but not Address.

I read this post. I thought my pojo structure is not unreasonable. Is it possible to do it?

Person table

id       - INT - AUTO-ID
email    - VARCHAR
address1 - VARCHAR
address2 - VARCHAR
address3 - VARCHAR
city     - VARCHAR
state    - VARCHAR
zip      - VARCHAR
country  - VARCHAR

Person.java

@Entity
public class Person {
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;    
    private String email;

    // this works, but does not work for international address!
    @Embedded
    private DomesticAddress address;      

    // this works, but does not work for international address!
    @Embedded
    @Target(DomesticAddress.class)
    private Address address;      

    // this does not work; being ignored! 
    @Embedded
    private Address address;      
    ....
}

Note: address is being declared only once. I just wanna show it in 3 different variations that I tried.

Address.java

public interface Address {
    ....
}

DomesticAddress.java

@Embeddable
public class DomesticAddress implements Address {
    private String address1;
    private String address2;
    private String city;
    private String state;
    private String zip;
    ....    
}

InternationalAddress.java

@Embeddable
public class InternationalAddress implements Address {
    private String address1;
    private String address2;
    private String address3;
    private String country;
    ....
}
Tin
  • 794
  • 5
  • 10
  • Think this through. `@Embedded` says that you're going to copy the properties of the embedded object into the column definition of the entity. How would that work if you used a polymorphic type like this? – chrylis -cautiouslyoptimistic- Jul 21 '17 at 02:29
  • Thanks, chrylis. I'm open for a suggestion if @Embedded is not something that I should use. I just wanna make it work with my current table and model classes. I'm also learning Hibernate, so I don't wanna change my design to make my life easier. – Tin Jul 21 '17 at 13:27

0 Answers0