Java.Hibernate.Beginner.What is hibernate.cfg.xml?

hibernate.cfg.xml is Hibernate’s central configuration file, traditionally used to define settings required for Hibernate to connect to the database and set up its behavior. It’s an XML file placed in your project’s classpath (usually in src/main/resources), and it’s used when you manually bootstrap Hibernate.

🔹 What does hibernate.cfg.xml contain?

  • Database connection details (URL, username, password, driver).
  • Hibernate properties (e.g., dialect, show_sql, hbm2ddl.auto).
  • Second-level cache settings (if any).
  • Mapping files or annotated classes to tell Hibernate which entities to persist.

🔹 Typical structure of hibernate.cfg.xml:

<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

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

    <!-- Hibernate properties -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>

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

    <!-- Optional: mapping XML files or annotated classes -->
    <mapping resource="com/example/User.hbm.xml"/>
    <!-- Or -->
    <!-- <mapping class="com.example.User"/> -->
  </session-factory>
</hibernate-configuration>

🔹 How is it used?
When you manually bootstrap Hibernate in a standalone app:

Configuration config = new Configuration();
config.configure("hibernate.cfg.xml"); // loads settings from XML
SessionFactory sessionFactory = config.buildSessionFactory();

🔹 In modern Spring Boot apps:
✅ You don’t need hibernate.cfg.xml — Spring Boot reads your application.properties or application.yml and auto-configures Hibernate.

Key takeaway:
hibernate.cfg.xml is Hibernate’s classic XML configuration file used to define database connection details, Hibernate properties, and entity mappings, especially in standalone (non-Spring) applications.

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