Home > Back-end >  How to ensure that only one instance of embeddable object can be created in a JPA entity?
How to ensure that only one instance of embeddable object can be created in a JPA entity?

Time:02-03

I am trying to generate JPA classes for legacy RDMS project.

There is an entity class Person, written in JPA. The entity Person has another Embeddale class called Address.

I can use set, list or map mapping for Embeddable Address. With any of these there can be multiple embedded objects in Person.

But the requirement is - there can be at most only one instance of embeddable object. How to achieve this requirement? I cannot use subclass entities, it has to be embeddable object only.

CodePudding user response:

You can use single value association something like below

    @Entity
public class Person {
  @Id
  private Long id;

  @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  @JoinColumn(name = "address_id")
  private Address address;
}

@Embeddable
public class Address {
  private String street;
  private String city;
}

You can read more about @oneToOne here

  • Related