A one-to-one mapping in JPA (Java Persistence API) represents a relationship where each entity instance in one table is associated with exactly one entity instance in another table. This tutorial will explain the concept with an example using EntityManager
for managing persistence. We'll cover the following steps:
Example Scenario
Let's assume we have two entities:
User
- Stores basic user information.UserProfile
- Stores additional user profile details.
Each User
has exactly one UserProfile
, and each UserProfile
belongs to exactly one User
.
Step-by-Step Implementation
Step 1: Create Entity Classes
- User Entity
- UserProfile Entity
Step 2: Persistence Configuration
Configure your persistence.xml
for JPA:
Step 3: Using EntityManager
Create a main class to persist and retrieve entities.
Key Points:
Mapping Annotation:
@OneToOne
: Declares the relationship.mappedBy
: Defines the owner of the relationship.@JoinColumn
: Specifies the foreign key column.
EntityManager:
- Use
em.persist()
to save entities. - Use
em.find()
to retrieve entities.
- Use
Cascade:
CascadeType.ALL
ensures that relatedUserProfile
is persisted when savingUser
.
This example sets up a one-to-one relationship and demonstrates persistence and retrieval using EntityManager
. Let me know if you'd like to dive deeper into any part!
Comments
Post a Comment