Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Understanding Object-Relational Mapping (ORM) Concepts


Object-Relational Mapping (ORM) is a programming technique used to map Java objects to relational database tables. This simplifies database interactions by abstracting SQL queries and enabling developers to interact with data through objects.

Step 1: What is ORM?

ORM bridges the gap between the object-oriented programming model and relational databases. It automatically handles the conversion of Java objects to database records and vice versa. Popular ORM frameworks in Java include Hibernate, JPA (Java Persistence API), and EclipseLink.

Step 2: Setting Up an ORM Framework

In this example, we will use Hibernate, a widely used ORM framework. Follow these steps to set up Hibernate:

Example Maven dependency for Hibernate:

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.6.0.Final</version>
            </dependency>
        

Example hibernate.cfg.xml configuration:

            <?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>
                    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
                    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/orm_db</property>
                    <property name="hibernate.connection.username">root</property>
                    <property name="hibernate.connection.password">password</property>
                    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                    <property name="hibernate.show_sql">true</property>
                    <property name="hibernate.hbm2ddl.auto">update</property>
                </session-factory>
            </hibernate-configuration>
        

Step 3: Creating Entity Classes

Entity classes represent database tables in Hibernate. These classes must follow these rules:

Example Entity Class:

            import javax.persistence.Entity;
            import javax.persistence.Id;
            import javax.persistence.GeneratedValue;
            import javax.persistence.GenerationType;

            @Entity
            public class Employee {
                @Id
                @GeneratedValue(strategy = GenerationType.IDENTITY)
                private int id;
                private String name;
                private double 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;
                }
            }
        

Step 4: Performing CRUD Operations

Hibernate allows you to perform Create, Read, Update, and Delete (CRUD) operations using its session methods.

Example of saving an entity:

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

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

                    // Create Session
                    Session session = factory.getCurrentSession();

                    try {
                        // Create an Employee object
                        Employee emp = new Employee();
                        emp.setName("John Doe");
                        emp.setSalary(50000);

                        // Begin transaction
                        session.beginTransaction();

                        // Save the employee object
                        session.save(emp);

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

                        System.out.println("Employee saved successfully!");
                    } finally {
                        factory.close();
                    }
                }
            }
        

Step 5: Querying the Database

Hibernate allows querying the database using HQL (Hibernate Query Language) or Criteria API.

Example of retrieving data using HQL:

            // Fetching all employees
            session.beginTransaction();
            List<Employee> employees = session.createQuery("from Employee").getResultList();
            for (Employee emp : employees) {
                System.out.println(emp.getName() + " - " + emp.getSalary());
            }
            session.getTransaction().commit();
        

Step 6: Advanced ORM Features

ORM frameworks offer additional features like lazy loading, caching, and associations (one-to-one, one-to-many, and many-to-many).

Example of a one-to-many relationship:

            import javax.persistence.*;
            import java.util.List;

            @Entity
            public class Department {
                @Id
                @GeneratedValue(strategy = GenerationType.IDENTITY)
                private int id;
                private String name;

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

                // 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 List<Employee> getEmployees() {
                    return employees;
                }

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

Conclusion

Object-Relational Mapping (ORM) simplifies database operations by abstracting SQL and providing an object-oriented approach. Using frameworks like Hibernate, developers can efficiently manage database interactions, focus on business logic, and reduce boilerplate code. With features like associations and caching, ORM is a powerful tool for modern enterprise applications.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java