Hibernate configuration file

Hibernate configuration file

The Hibernate configuration file, typically named hibernate.cfg.xml, is a crucial component in Hibernate framework setup. It contains configuration settings and mapping details that are essential for establishing a connection to the database and specifying how Java objects relate to database tables.

Key Points

  1. Configuration Settings: Contains properties such as database connection details, dialect, driver class, URL, username, password, and various Hibernate-specific settings.
  2. Mapping Details: Defines the classes that Hibernate will manage, specifying how these classes are mapped to database tables.
  3. Transaction Management: Configures transaction management settings.
  4. Caching: Specifies caching strategies and settings.

Hibernate configuration file

Hibernate Configuration File (hibernate.cfg.xml):
Here is an example of a typical hibernate.cfg.xml configuration file:

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 settings -->
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:mem:test</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>
        
        <!-- JDBC connection pool settings -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        
        <!-- Dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>
        
        <!-- Drop and re-create the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- Mention annotated class -->
        <mapping class="com.example.User"/>
    </session-factory>
</hibernate-configuration>


 2. Entity Class: 

java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String email;
    
    // Constructors
    public User() {}
    
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }
    
    // 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;
    }
    
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
}


 3. Main Application Code: 

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

public class HibernateDemo {
    public static void main(String[] args) {
        // Create a Configuration instance
        Configuration configuration = new Configuration().configure();

        // Build a SessionFactory from the Configuration
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        // Obtain a Session from the SessionFactory
        Session session = sessionFactory.openSession();

        // Begin a transaction
        Transaction transaction = session.beginTransaction();

        // Create a new User entity
        User user = new User("John Doe", "john.doe@example.com");

        // Save the User entity
        session.save(user);

        // Commit the transaction
        transaction.commit();

        // Retrieve the User entity
        User retrievedUser = session.get(User.class, user.getId());
        System.out.println("Retrieved User: " + retrievedUser.getName() + ", " + retrievedUser.getEmail());

        // Close the Session
        session.close();

        // Close the SessionFactory
        sessionFactory.close();
    }
}

Explanation of the Example:

1.  Hibernate Configuration File (hibernate.cfg.xml):

  • Database Connection Settings:  Configures the JDBC driver, URL, username, and password.
  • Connection Pool Settings:  Sets the minimum and maximum size of the connection pool, timeout, and other pooling parameters.
  • Dialect:  Specifies the SQL dialect (in this case, H2 dialect) that Hibernate should use.
  • Show SQL:  Enables the logging of SQL statements to the console.
  • Schema Generation:  The hibernate.hbm2ddl.auto property is set to update, which means Hibernate will automatically update the database schema.
  • Entity Mapping:  Specifies the User entity class to be managed by Hibernate.

2.  Entity Class

  • The User class is annotated with @Entity to mark it as a JPA entity.
  • The @Id annotation specifies the primary key, and @GeneratedValue indicates that the ID should be generated automatically.
  • Includes constructors, getters, and setters.

3.  Main Application Code

  • A Configuration instance is created and configured using hibernate.cfg.xml.
  • A SessionFactory is built from the configuration.
  • A Session is obtained from the SessionFactory.
  • A Transaction is started, and a User entity is created and saved.
  • The transaction is committed, and the User entity is retrieved and printed.
  • The Session and SessionFactory are closed.

Homepage

Readmore