Home:ALL Converter>Address Entity in multiple Entities without specifying it

Address Entity in multiple Entities without specifying it

Ask Time:2021-12-11T18:34:55         Author:Simagdo

Json Formatter

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() {

    }

}

Author:Simagdo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70314397/address-entity-in-multiple-entities-without-specifying-it
yy