Java Technologies Hibernate Annotations এর মাধ্যমে Mapping গাইড ও নোট

322

Hibernate ORM (Object-Relational Mapping) Java objects এবং relational database tables এর মধ্যে সম্পর্ক তৈরি করার একটি শক্তিশালী টুল। Hibernate ORM ব্যবহার করে, Java objects (POJOs) কে database tables এর সাথে সম্পর্কিত করতে annotations ব্যবহার করা যায়, যা XML configuration এর পরিবর্তে আরো সহজ এবং কম্প্যাক্টভাবে mapping পরিচালনা করতে সহায়ক।

Hibernate annotations আপনাকে Java classes এবং database tables এর মধ্যে সম্পর্ক স্থাপন করতে, primary key, column mapping, এবং associations (relationships) নির্ধারণ করতে সাহায্য করে।

Hibernate Annotations এর মাধ্যমে Mapping-এর মূল উপাদানগুলি

Hibernate-এ annotations ব্যবহার করে object-relational mapping কনফিগারেশন করা যেতে পারে, যেমন:

  1. @Entity: এই অ্যানোটেশনটি Hibernate কে জানায় যে এটি একটি entity এবং এটি ডেটাবেস টেবিলের সাথে সম্পর্কিত।
  2. @Table: এটি database table এর নাম সুনির্দিষ্ট করে দেয়, যা Entity ক্লাসের সাথে সম্পর্কিত।
  3. @Id: এটি টেবিলের primary key নির্ধারণ করে।
  4. @GeneratedValue: এটি primary key-এর auto-generation স্ট্রাটেজি নির্ধারণ করে।
  5. @Column: এটি ক্লাসের একটি ফিল্ডকে একটি column এর সাথে ম্যাপ করে।
  6. @OneToMany, @ManyToOne, @ManyToMany, @OneToOne: এই অ্যানোটেশনগুলি associations (relationship) ম্যাপ করতে ব্যবহৃত হয়।

Hibernate Annotations এর মাধ্যমে Mapping এর উদাহরণ

ধরা যাক, আমাদের একটি Employee এবং Department Entity Class রয়েছে, যেখানে One-to-Many relationship রয়েছে। এক Department একাধিক Employee এর সাথে সম্পর্কিত থাকতে পারে।

Step 1: Entity Class তৈরি করা

Employee Entity Class:
import javax.persistence.*;

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "salary")
    private double salary;

    @ManyToOne
    @JoinColumn(name = "department_id") // Foreign key column for the Department entity
    private Department department;

    public Employee() {}

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    // Getters and setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}
Department Entity Class:
import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "department")
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
    private Set<Employee> employees;

    public Department() {}

    public Department(String name) {
        this.name = name;
    }

    // Getters and setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(Set<Employee> employees) {
        this.employees = employees;
    }
}

Step 2: Hibernate Configuration File

Hibernate কনফিগারেশন ফাইলে ডেটাবেস সংযোগ এবং entity class এর ম্যাপিং নির্ধারণ করতে হবে। নিচে একটি সাধারণ hibernate.cfg.xml কনফিগারেশন ফাইলের উদাহরণ দেওয়া হলো:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>
        <!-- JDBC connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>

        <!-- Hibernate dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- Enable batch processing -->
        <property name="hibernate.jdbc.batch_size">20</property>

        <!-- Enable second-level cache -->
        <property name="hibernate.cache.use_second_level_cache">true</property>

        <!-- Show SQL -->
        <property name="hibernate.show_sql">true</property>

        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Mapping the entity classes -->
        <mapping class="com.example.model.Employee"/>
        <mapping class="com.example.model.Department"/>
    </session-factory>

</hibernate-configuration>

Step 3: Data Insertion with Hibernate

এখন, Hibernate ব্যবহার করে আমরা Employee এবং Department এর ইনস্ট্যান্স তৈরি এবং ডেটাবেসে সেভ করতে পারি।

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

public class HibernateApp {
    public static void main(String[] args) {
        // Create session factory
        SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
                                                  .addAnnotatedClass(Employee.class)
                                                  .addAnnotatedClass(Department.class)
                                                  .buildSessionFactory();
        
        // Create session
        Session session = factory.getCurrentSession();

        try {
            // Create new Department object
            Department department = new Department("IT");

            // Create new Employee objects
            Employee emp1 = new Employee("John Doe", 50000);
            Employee emp2 = new Employee("Jane Doe", 60000);

            // Set the department for each employee
            emp1.setDepartment(department);
            emp2.setDepartment(department);

            // Start a transaction
            session.beginTransaction();

            // Save the department (this will also save the employees because of CascadeType.ALL)
            session.save(department);

            // Commit the transaction
            session.getTransaction().commit();

            System.out.println("Saved department and employees successfully!");
        } finally {
            factory.close();
        }
    }
}

Explanation:

  1. @ManyToOne: Employee class-এ @ManyToOne অ্যানোটেশন ব্যবহার করা হয়েছে, যা Employee এবং Department এর মধ্যে Many-to-One সম্পর্ক স্থাপন করে। অর্থাৎ, এক Department একাধিক Employee এর সাথে সম্পর্কিত হতে পারে।
  2. @OneToMany: Department class-এ @OneToMany অ্যানোটেশন ব্যবহার করা হয়েছে, যা reverse সম্পর্ক বোঝায়। একটি Department এর একাধিক Employee থাকতে পারে, এবং এই সম্পর্কের জন্য mappedBy ব্যবহার করা হয় যাতে Hibernate জানাতে পারে যে, সম্পর্কটি কিভাবে পরিচালিত হবে (এখানে Employee class এর department প্রপার্টি দ্বারা)।
  3. CascadeType.ALL: এটি Employee অবজেক্টের উপর cascade অপারেশন কার্যকর করে, অর্থাৎ যখন Department সেভ হয়, তখন তার সাথে সম্পর্কিত Employees গুলি স্বয়ংক্রিয়ভাবে সেভ হয়ে যাবে।

Step 4: HQL Query with Mapping

এখন, HQL (Hibernate Query Language) ব্যবহার করে, আপনি Department এবং Employee সম্পর্কিত ডেটা রিট্রিভ করতে পারেন। উদাহরণস্বরূপ:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class HibernateApp {
    public static void main(String[] args) {
        // Create session factory
        SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
                                                  .addAnnotatedClass(Employee.class)
                                                  .addAnnotatedClass(Department.class)
                                                  .buildSessionFactory();
        
        // Create session
        Session session = factory.getCurrentSession();

        try {
            // Start a transaction
            session.beginTransaction();

            // HQL query to get all employees in the "IT" department
            Query<Employee> query = session.createQuery("from Employee e where e.department.name='IT'", Employee.class);

            // Execute the query and get the result list
            List<Employee> employees = query.getResultList();

            // Display the employees
            for (Employee emp : employees) {
                System.out.println(emp.getName() + "

works in the " + emp.getDepartment().getName() + " department"); }

        // Commit the transaction
        session.getTransaction().commit();
    } finally {
        factory.close();
    }
}

}


---

### **Conclusion**

- Hibernate Annotations ব্যবহার করে **Entity Classes** এবং **database tables** এর মধ্যে সম্পর্ক স্থাপন করা সহজ এবং কার্যকর। 
- **One-to-Many** সম্পর্ক তৈরি করার জন্য **`@OneToMany`** এবং **`@ManyToOne`** অ্যানোটেশনগুলি ব্যবহার করা হয়, যা Java objects এবং ডেটাবেস টেবিলের মধ্যে সম্পর্ক সঠিকভাবে ম্যাপ করে।
- Hibernate এ **HQL (Hibernate Query Language)** ব্যবহার করে আপনি Entity ক্লাসের মধ্যে সম্পর্কিত ডেটা সহজে রিট্রিভ করতে পারেন এবং ডেটাবেসের সাথে যোগাযোগ করতে পারেন।
Content added By
Promotion

Are you sure to start over?

Loading...