Steps to Implementation
1. Define the Entities:
We can create the two entity classes Person and Address and it can establish the one-to-one relationship between them using the annotations of the JPA application.
Person Entity:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
private Address address;
// Constructors, getters, and setters
}
Address Entity:
@Entity
public class Address {
@Id
private Long id;
@OneToOne
@MapsId
private Person person;
private String city;
// Constructors, getters, and setters
}
2. Implement the Mapping:
We can use the annotations to define the mapping between the entities and it can annotate the corresponding fields in the both entities with @OneToOne.
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
private Address address;
3. Handles the Foreign Key:
We can ensures that the foreign key referencing the primary key of the one entity is present in the other entity of the application.
4. Test the Mapping:
We can persist the instances of the entities and retrieves them to the verify the mapping of the JPA application.
// Code to persist entities and retrieve them to verify the mapping
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU_NAME");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Person person = new Person();
person.setName("John Doe");
em.persist(person);
Address address = new Address();
address.setPerson(person);
address.setCity("New York");
em.persist(address);
em.getTransaction().commit();
// Retrieve person and address
Person retrievedPerson = em.find(Person.class, person.getId());
Address retrievedAddress = retrievedPerson.getAddress();
System.out.println("Person: " + retrievedPerson.getName());
System.out.println("Address: " + retrievedAddress.getCity());
em.close();
emf.close();
JPA One-to-One Mapping
In Java, JPA can define the Java Persistence API, One-to-one mapping is the common association relationship where one instance of the entity is associated with exactly one instance of another entity.