Hibernate One-to-One Mapping

A one-to-one (1:1) relationship means that one entity is associated with exactly one other entity.

For example:

  • One User has one Profile.
  • One Employee has one Address.

Ways to Implement One-to-One Mapping:

Approach

Description

Using @OneToOne with @JoinColumn

Uses a foreign key in one table.

Using @OneToOne with mappedBy

Uses a bidirectional relationship.

Using @PrimaryKeyJoinColumn

Uses shared primary keys.


One-to-One with @JoinColumn:

One User has One Profile

  • User Table → Stores id, name, and a reference to profile_id.
  • Profile Table → Stores id and bio.
User.java
import jakarta.persistence.*;

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "profile_id") // Foreign key in User table
private Profile profile;

// Constructors
public User() {}
public User(String name, Profile profile) {
this.name = name;
this.profile = profile;
}
}
Profile.java
import jakarta.persistence.*;

@Entity
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String bio;

// Constructors
public Profile() {}
public Profile(String bio) {
this.bio = bio;
}
}
Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {
public static void main(String[] args) {
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(User.class).addAnnotatedClass(Profile.class).buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Create User and Profile
Profile profile = new Profile("Java Developer");
User user = new User("John Doe", profile);
// Save the student
session.persist(user); // Hibernate will generate an INSERT SQL statement
transaction.commit();
session.close();
sessionFactory.close();
System.out.println("Insert data successfully!");
}
}

Output

Table name : profiles

id bio
1 Java Developer

Table name : users

id name profile_id
1 John Doe 1

One-to-One with mappedBy (Bidirectional):

  • The Profile entity owns the relationship (foreign key is in User).
  • mappedBy="profile" tells Hibernate that Profile is responsible.
User.java
import jakarta.persistence.*;

@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Profile profile;

public User() {}
public User(String name) {
this.name = name;
}
public void setProfile(Profile profile) {
this.profile = profile;
profile.setUser(this); // To maintain bidirectional relationship
}
}
Profile.java
import jakarta.persistence.*;

@Entity
@Table(name = "profile")
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String bio;

@OneToOne
@JoinColumn(name = "user_id") // This column will store the foreign key
private User user;

public Profile() {}
public Profile(String bio) {
this.bio = bio;
}
}

Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(User.class).addAnnotatedClass(Profile.class).buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Create User and Profile
Profile profile = new Profile("Java Developer");
User user = new User("John Doe");
user.setProfile(profile);
// Save the student
session.persist(user); // Hibernate will generate an INSERT SQL statement
transaction.commit();
session.close();
sessionFactory.close();
System.out.println("Insert data successfully!");
}
}

Output

Table name : users

id name
1 John Doe

Table name : profiles

id bio user_id
1 Java Developer 1

One-to-One with @PrimaryKeyJoinColumn (Shared Primary Key):

  • Both User and Profile share the same primary key.
User.java
import jakarta.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Profile profile;
public User() {}
public User(String name) {
this.name = name;
}
public void setProfile(Profile profile) {
this.profile = profile;
profile.setUser(this); // To maintain bidirectional relationship
}
}
Profile.java
import jakarta.persistence.*;
@Entity
@Table(name = "profile")
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String bio;
@OneToOne
@PrimaryKeyJoinColumn // This ensures that the primary key is also a foreign key
private User user;
public Profile() {}
public Profile(String bio) {
this.bio = bio;
}
}
Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(User.class).addAnnotatedClass(Profile.class).buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Create User and Profile
Profile profile = new Profile("Java Developer");
User user = new User("John Doe");
user.setProfile(profile);
// Save the student
session.persist(user); // Hibernate will generate an INSERT SQL statement
transaction.commit();
session.close();
sessionFactory.close();
System.out.println("Insert data successfully!");
}
}

Output

Table name : users

id name
1 John Doe

Table name : profiles

id bio
1 Java Developer

Create Read Update Delete (CRUD):

In this guide, we will implement CRUD (Create, Read, Update, Delete) operations for a One-to-One Mapping using Hibernate.

User.java
import jakarta.persistence.*;

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "profile_id") // Foreign key in User table
private Profile profile;

// Constructors
public User() {}
public User(String name, Profile profile) {
this.name = name;
this.profile = profile;
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public Profile getProfile() { return profile; }
}
Profile.java
import jakarta.persistence.*;

@Entity
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String bio;

// Constructors
public Profile() {}
public Profile(String bio) {
this.bio = bio;
}
public void setBio(String bio) { this.bio = bio;}
public String getBio() { return bio;}
}
HibernateUtil.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
return new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(User.class)
.addAnnotatedClass(Profile.class)
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static Session getSession() {
return sessionFactory.openSession(); // Opens a new session when needed
}

public static void shutdown() {
sessionFactory.close(); // Close SessionFactory when the application shuts down
}
}
Main.java
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Main {
public static void main(String[] args) {
// Create Data
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
Profile profile = new Profile("Software Engineer");
User user = new User("Alice",profile);
session.persist(user); // Save user and profile due to CascadeType.ALL
transaction.commit();
session.close();
System.out.println("Created successfully!");

// Read Data
session = HibernateUtil.getSession();
user = session.get(User.class, 1L);
System.out.println(user.getName() + " - " + user.getProfile().getBio());
session.close();

// Update Data
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
user = session.get(User.class, 1L);
if (user != null) {
user.setName("Updated Alice");
user.getProfile().setBio("Updated Bio");
session.update(user);
}
transaction.commit();
session.close();
System.out.println("Updated successfully!");

// Delete Data
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
user = session.get(User.class, 1L);
if (user != null) {
session.delete(user); // Also deletes profile due to CascadeType.ALL
}
transaction.commit();
session.close();
System.out.println("Deleted successfully!");

HibernateUtil.shutdown(); // Close sessionFactory
}
}

Output


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.