Java.Hibernate.Beginner.What is a Hibernate mapping file?

What is a Hibernate mapping file?

Answer:
A Hibernate mapping file is an XML file (usually ending with .hbm.xml) that tells Hibernate how to map a Java class to a database table, and how the class’s fields map to table columns.


🔹 What it does:

  • Defines the mapping between your entity’s properties and the database schema.
  • Specifies primary keys, column names, data types, and relationships (one-to-one, one-to-many, etc.).
  • Lets you customize mappings without modifying Java code (especially useful before JPA annotations became common).

🔹 Example Hibernate mapping file (User.hbm.xml):

<!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.User" table="users">
    <id name="id" column="id">
      <generator class="native"/>
    </id>
    <property name="username" column="username"/>
    <property name="email" column="email"/>
  </class>
</hibernate-mapping>

✅ This tells Hibernate to map com.example.User to the users table, map id as the primary key, and map username and email fields to their respective columns.

🔹 How it’s used:

  • You register mapping files in hibernate.cfg.xml:
<mapping resource="com/example/User.hbm.xml"/>

Or add them programmatically:

config.addResource("com/example/User.hbm.xml");

🔹 Modern alternative:

  • JPA annotations (@Entity, @Table, @Column, etc.) are now the standard way to define mappings directly in Java code, making mapping files optional in most modern apps.

Key takeaway:
A Hibernate mapping file defines the bridge between your object model and relational database schema using XML — but today, most developers prefer annotations for clarity and maintainability.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.