Issue
I have a one-to-many relationship with Customer and Address, but I'm not sure how to represent this with JPA. I don't want use @OneToMany for the AddressEntity's in CustomerEntity because I want to avoid wrapping it in a Collection.
I'm wondering what annotation or even other strategies I can use to maintain the relationship where one customer will, for simplicity, always have two addresses. Any suggestions are appreciated!
Address Entity
@Data
@NoArgsConstructor
@Entity(name = "address")
public class AddressEntity
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@?
private CustomerEntity customer;
}
Customer Entity
@Data
@NoArgsConstructor
@Entity(name = "customer")
public class CustomerEntity
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@?
private AddressEntity shippingAddress;
@?
private AddressEntity billingAddress;
}
Solution
For the case when an address can belong different customers.
@Entity
public class AddressEntity
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
}
@Entity
public class CustomerEntity
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private AddressEntity shippingAddress;
@ManyToOne
private AddressEntity billingAddress;
}
if each customer has unique address, better to store the addresses in the same customer record.
You can create class EmbeddedAddress
and use @Embedded
and @Embeddable
annotations.
Answered By - v.ladynev