Menu

Configuring Hibernate

Configuring Hibernate

Configuration Options

Hibernate needs to know which database to connect to and which classes to map. You can provide this in three ways.

  • hibernate.cfg.xml, the Hibernate native XML file.
  • hibernate.properties, a plain properties file.
  • persistence.xml, the standard Jakarta Persistence file placed in META-INF.

This handbook uses hibernate.cfg.xml, since it keeps connection settings and mapped classes in one place.

A Basic Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="jakarta.persistence.jdbc.url">jdbc:h2:mem:testdb</property>
        <property name="jakarta.persistence.jdbc.user">sa</property>
        <property name="jakarta.persistence.jdbc.password"></property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <mapping class="com.example.Student"/>
    </session-factory>
</hibernate-configuration>

Code Explanation:

  • The jakarta.persistence.jdbc.* properties are the standard names for the database URL, user, and password.
  • hibernate.show_sql prints the generated SQL to the console, which helps while learning.
  • hibernate.format_sql prints that SQL in a readable multi-line form.
  • The mapping element registers an entity class. Every entity must be listed here or added in code.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details