What is hibernate mapping file?

What is hibernate mapping file?

A Hibernate mapping file is an XML configuration file used to define the relationship between Java classes (entities) and database tables. It specifies how the properties of a class map to columns in a table and can also define associations, inheritance, and other relationships between entities.

Key Points about Hibernate Mapping Files:

  • Class to Table Mapping : Defines how a Java class maps to a database table.
  • Property to Column Mapping : Specifies how the fields or properties of the Java class map to columns in the table.
  • Associations : Defines relationships between entities, such as one-to-one, one-to-many, many-to-one, and many-to-many.
  • Inheritance : Configures inheritance hierarchies between entities.
  • Custom SQL : Allows custom SQL for CRUD operations and queries.

hibernate mapping file

Example of Hibernate Mapping File

Here’s a step-by-step example to demonstrate the use of a Hibernate mapping file.

  1. Configuration File (hibernate.cfg.xml) : Configure Hibernate to use the mapping file.

Example

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>
        <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>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <mapping resource="com/example/MyEntity.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Example
2.  Mapping File (MyEntity.hbm.xml) :
   - Define the mapping between the MyEntity class and the my_entity table.

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.example.MyEntity" table="my_entity">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" column="name"/>
    </class>
</hibernate-mapping>

Example
3.  Entity Class (MyEntity.java) :
   - Define the entity class without any Hibernate or JPA annotations.

java
public class MyEntity {
    private Long id;
    private String name;

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

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

    public String getName() {
        return name;
    }

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

Example
4.  Hibernate Utility Class (HibernateUtil.java) :
   - Configure and provide a method to get the Hibernate Session.

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

Example
5.  Main Application Class (MainApp.java) :
   - Demonstrate the use of Hibernate to save and query entities.

java
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MainApp {
    public static void main(String[] args) {
        // Get Session
        Session session = HibernateUtil.getSession();

        // Begin transaction
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();

            // Save an entity
            MyEntity entity = new MyEntity();
            entity.setName("Test Entity");
            session.save(entity);

            // Commit transaction
            transaction.commit();

            // Query the entity
            MyEntity result = session.get(MyEntity.class, entity.getId());
            System.out.println("Queried Entity Name: " + result.getName());

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

Homepage

Readmore