Home > Software design >  Address Entity in multiple Entities without specifying it
Address Entity in multiple Entities without specifying it

Time:12-12

i am currently building an Application with Spring and i have a Question there:

I want to have an Entity Address which looks like this:

@Entity(name = "Address")
@Table(name = "address")
@EntityListeners(AuditingEntityListener.class)
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "city")
    private String city;
    @Column(name = "country")
    private String country;
    @Column(name = "postalcode")
    private String postalCode;
    @Column(name = "state")
    private String state;
    @Column(name = "street")
    private String street;

    public Address() {

    }

}

I want to use this Address Entity in multiple Entities, for example in the User or Order Entity. Later, i will like to have many Entities which need an Address. But i don't want to specify each Relation in the Address Entity, otherwise it will get to complex. Is it possible to have a Link from the User to the Address with only specifying this Link in the User Entity?

My User Entity looks something like this:

@Entity(name = "User")
@Table(name = "User")
@EntityListeners(AuditingEntityListener.class)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "username")
    private String userName;
    @OneToOne(
            mappedBy = "address",
            orphanRemoval = true,
            cascade = {
                    CascadeType.PERSIST,
                    CascadeType.REMOVE
            }
    )
    private Address billingAddress;

    public User() {

    }

}

CodePudding user response:

Yes, it is possible, but you don't actually need mappedBy property, otherwise you are telling JPA to search for a address property in the other side of the relationship (that you actually want to be unidirectional):

@Entity(name = "User")
@Table(name = "User")
@EntityListeners(AuditingEntityListener.class)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    
    @Column(name = "username")
    private String userName;
    
    @OneToOne(
            orphanRemoval = true,
            cascade = { CascadeType.PERSIST, CascadeType.REMOVE }
    )
    private Address billingAddress;

    public User() {

    }
}

You can read more about this in the following online resources:

  • Related