Implement relationships in hibernate

Implement relationships in hibernate

In Hibernate, relationships between entities can be defined using annotations or XML mappings. The common types of relationships include:

  1. One-to-One : Each entity instance is associated with one and only one instance of another entity.
  2. One-to-Many : One entity instance is associated with multiple instances of another entity.
  3. Many-to-One : Multiple instances of one entity are associated with one instance of another entity.
  4. Many-to-Many : Multiple instances of one entity are associated with multiple instances of another entity.

Types of Relationships in hibernate

  • One-to-One Relationship : Represented using the @OneToOne annotation.
  • One-to-Many Relationship : Represented using the @OneToMany annotation on the parent side and @ManyToOne annotation on the child side.
  • Many-to-One Relationship : Represented using the @ManyToOne annotation.
  • Many-to-Many Relationship : Represented using the @ManyToMany annotation.

relationships in hibernate

Implement relationships in hibernate Example

Let’s implement each type of relationship using Java and Hibernate.

Step 1: Define the Entities
One-to-One Relationship 

java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Address {
    @Id
    private int id;
    private String street;
    private String city;

    @OneToOne(mappedBy = "address")
    private User user;

    // Getters and setters
}

@Entity
public class User {
    @Id
    private int id;
    private String name;

    @OneToOne
    private Address address;

    // Getters and setters
}


 One-to-Many and Many-to-One Relationship 

java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.Set;

@Entity
public class Department {
    @Id
    private int id;
    private String name;

    @OneToMany(mappedBy = "department")
    private Set<Employee> employees;

    // Getters and setters
}

@Entity
public class Employee {
    @Id
    private int id;
    private String name;

    @ManyToOne
    private Department department;

    // Getters and setters
}


 Many-to-Many Relationship 

java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import java.util.Set;

@Entity
public class Student {
    @Id
    private int id;
    private String name;

    @ManyToMany(mappedBy = "students")
    private Set<Course> courses;

    // Getters and setters
}

@Entity
public class Course {
    @Id
    private int id;
    private String name;

    @ManyToMany
    private Set<Student> students;

    // Getters and setters
}

Step 2: Configure Hibernate
 hibernate.cfg.xml 

xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        
        <!-- Specify dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Update the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Mappings -->
        <mapping class="com.example.Address"/>
        <mapping class="com.example.User"/>
        <mapping class="com.example.Department"/>
        <mapping class="com.example.Employee"/>
        <mapping class="com.example.Student"/>
        <mapping class="com.example.Course"/>
    </session-factory>
</hibernate-configuration>

Step 3: Main Application

java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        // Set up the Hibernate session factory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            // One-to-One Relationship
            Address address = new Address();
            address.setId(1);
            address.setStreet("123 Main St");
            address.setCity("Springfield");

            User user = new User();
            user.setId(1);
            user.setName("John Doe");
            user.setAddress(address);

            session.save(address);
            session.save(user);

            // One-to-Many and Many-to-One Relationship
            Department department = new Department();
            department.setId(1);
            department.setName("Engineering");

            Employee employee1 = new Employee();
            employee1.setId(1);
            employee1.setName("Alice");
            employee1.setDepartment(department);

            Employee employee2 = new Employee();
            employee2.setId(2);
            employee2.setName("Bob");
            employee2.setDepartment(department);

            session.save(department);
            session.save(employee1);
            session.save(employee2);

            // Many-to-Many Relationship
            Course course1 = new Course();
            course1.setId(1);
            course1.setName("Math");

            Course course2 = new Course();
            course2.setId(2);
            course2.setName("Science");

            Student student1 = new Student();
            student1.setId(1);
            student1.setName("Charlie");

            Student student2 = new Student();
            student2.setId(2);
            student2.setName("Dave");

            course1.getStudents().add(student1);
            course1.getStudents().add(student2);
            course2.getStudents().add(student1);

            student1.getCourses().add(course1);
            student1.getCourses().add(course2);
            student2.getCourses().add(course1);

            session.save(course1);
            session.save(course2);
            session.save(student1);
            session.save(student2);

            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
            sessionFactory.close();
        }
    }
}

Explanation of the Implement relationships in hibernate

1. Define the Entities :

  • One-to-One Relationship : The User entity has a one-to-one relationship with the Address entity.
  • One-to-Many and Many-to-One Relationship : The Department entity has a one-to-many relationship with the Employee entity, and each Employee entity has a many-to-one relationship with the Department entity.
  • Many-to-Many Relationship : The Student and Course entities have a many-to-many relationship.

2.  Configure Hibernate :

The hibernate.cfg.xml file configures Hibernate to connect to a MySQL database and update the schema on startup.

3.  Main Application :

  • We create and save entities representing different types of relationships.
  • The relationships are established and saved in the database.

This example demonstrates how to implement various types of relationships in Hibernate using Java.

Homepage

Readmore