Explain About Mapping Files in Hibernate

Mapping files forms the core of any database mapping tools. These files contain field to field mapping, usually this mapping occurs between classes and attributes. After mapping files they can be persist to the database. Tags can be used to indicate the presence of a primary key.

In Hibernate, mapping files are used to define the relationship between Java objects and database tables. These files specify how the fields of Java objects are mapped to the columns of database tables and define the associations between different entities.

The mapping files in Hibernate are typically XML files with a .hbm.xml extension. These files contain metadata that Hibernate uses to understand the mapping between Java objects and database tables. Here are the key elements you would find in a Hibernate mapping file:

  1. Class Element:
    • The <class> element is used to map a Java class to a database table. It contains attributes like name (fully qualified class name), table (database table name), and schema (database schema name).
    xml
    <class name="com.example.model.Employee" table="employee">
    <!-- Mapping details go here -->
    </class>
  2. Property Element:
    • The <property> element is used to map a Java class property to a database column. It contains attributes like name (property name) and column (database column name).
    xml
    <property name="firstName" column="first_name" />
  3. Id Element:
    • The <id> element is used to map the primary key of the entity. It specifies the primary key column and its generation strategy.
    xml
    <id name="id" column="employee_id">
    <generator class="increment" />
    </id>
  4. Association Elements:
    • Hibernate supports various types of associations like one-to-one, one-to-many, many-to-one, and many-to-many. These associations are defined using elements like <one-to-one>, <one-to-many>, <many-to-one>, and <many-to-many>.
    xml
    <set name="projects" table="employee_projects" cascade="all">
    <key column="employee_id" />
    <one-to-many class="com.example.model.Project" />
    </set>
  5. Mapping Relationships:
    • Relationships between entities are mapped using properties like many-to-one, one-to-many, one-to-one, and many-to-many. These properties define how different entities are related to each other.
    xml
    <many-to-one name="department" class="com.example.model.Department" column="department_id" />

By configuring these mapping details in the Hibernate mapping file, you provide the necessary information for Hibernate to generate SQL queries and manage the persistence of Java objects in the database. Mapping files are crucial for defining the Object-Relational Mapping (ORM) between your Java application and the underlying database.