Configuration Management


Configuration Management Interview with follow-up questions

1. What is the role of the Configuration object in Hibernate?

In Hibernate 6 (and modern Spring Boot 3 applications), the Configuration object's role has been largely absorbed by the JPA Persistence bootstrap API and Spring's auto-configuration, but it is still relevant for programmatic or non-Spring setups.

What the Configuration object does:

  1. Specifies database connection settings — URL, driver, username, password, dialect.
  2. Registers entity mappings — either by scanning annotated classes or by loading .hbm.xml mapping files.
  3. Sets Hibernate properties — cache settings, DDL mode, batch size, etc.
  4. Builds the SessionFactory — the heavyweight, application-scoped object that represents one database.

Programmatic usage (Hibernate 6, without Spring):

import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

SessionFactory sessionFactory = new Configuration()
    .setProperty("hibernate.connection.url", "jdbc:postgresql://localhost/mydb")
    .setProperty("hibernate.connection.username", "user")
    .setProperty("hibernate.connection.password", "secret")
    .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")
    .setProperty("hibernate.hbm2ddl.auto", "validate")
    .addAnnotatedClass(Product.class)
    .addAnnotatedClass(Order.class)
    .buildSessionFactory();

In Spring Boot 3 (most common setup):

Spring Boot auto-configures Hibernate via application.properties — no Configuration object is instantiated manually:

spring.datasource.url=jdbc:postgresql://localhost/mydb
spring.datasource.username=user
spring.datasource.password=secret
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=validate

Spring's LocalContainerEntityManagerFactoryBean internally creates and manages the SessionFactory.

Interview angle: Know the Configuration API for standalone/legacy scenarios, but emphasise that in Spring Boot 3 projects it is replaced by application.properties + JPA auto-configuration. Also note hibernate.cfg.xml is an alternative to programmatic configuration.

↑ Back to top

Follow-up 1

How do you create a Configuration object?

To create a Configuration object in Hibernate, you can use the following code:

Configuration configuration = new Configuration();

Follow-up 2

What are some of the methods provided by the Configuration object?

The Configuration object in Hibernate provides several methods to configure Hibernate, such as:

  • configure(): Loads the configuration from the default configuration file (hibernate.cfg.xml).
  • addAnnotatedClass(Class> annotatedClass): Adds a persistent class annotated with @Entity to the configuration.
  • setProperty(String propertyName, String value): Sets a configuration property.
  • addResource(String resourceName): Adds a mapping resource (XML file) to the configuration.
  • buildSessionFactory(): Builds a SessionFactory based on the configuration.

These are just a few examples, and there are many more methods available.

Follow-up 3

How does the Configuration object help in bootstrapping Hibernate?

The Configuration object plays a crucial role in bootstrapping Hibernate. It is used to specify the configuration properties, such as the database connection details, dialect, and mapping information. It also allows you to add annotated classes or XML mapping files to the configuration. Once the Configuration object is properly configured, it can be used to build a SessionFactory, which is the main entry point for interacting with Hibernate.

Follow-up 4

Can you modify the Configuration object after it's created?

Yes, you can modify the Configuration object after it's created. The Configuration object provides various methods to add or modify configuration properties, add annotated classes or XML mapping files, and customize the Hibernate configuration. However, it's important to note that once the Configuration object is used to build a SessionFactory, any modifications made to the Configuration object will not have any effect on the already built SessionFactory.

2. What is the purpose of the hibernate.cfg.xml file?

hibernate.cfg.xml is Hibernate's primary XML configuration file for standalone (non-Spring) applications. It centralises database connection settings, dialect selection, entity mappings, and Hibernate behaviour properties in one place.

Location: Placed on the classpath root (src/main/resources/hibernate.cfg.xml).

Structure and key settings:








        org.postgresql.Driver
        jdbc:postgresql://localhost:5432/mydb
        user
        secret


        org.hibernate.dialect.PostgreSQLDialect


        validate


        true
        true


        5
        20








Loading in code:

SessionFactory sf = new Configuration()
    .configure()          // reads hibernate.cfg.xml from classpath
    .buildSessionFactory();

Hibernate 6 / Spring Boot 3 context:

Spring Boot applications do not use hibernate.cfg.xml. Spring Boot reads application.properties (or application.yml) and wires Hibernate through JPA auto-configuration. hibernate.cfg.xml is relevant for:

  • Standalone Hibernate applications
  • Legacy projects not yet migrated to Spring Boot
  • Interview questions about Hibernate fundamentals independent of Spring

hbm2ddl.auto values — frequently asked:

  • none — make no schema changes (production default)
  • validate — verify schema matches mappings; fail if not
  • update — add missing columns/tables (risky in production)
  • create — drop and recreate schema on startup
  • create-drop — create on startup, drop on SessionFactory close (for testing)
↑ Back to top

Follow-up 1

What are some of the properties you can set in this file?

Some of the properties that can be set in the hibernate.cfg.xml file include:

  • hibernate.connection.url: The URL of the database
  • hibernate.connection.username: The username for the database connection
  • hibernate.connection.password: The password for the database connection
  • hibernate.dialect: The SQL dialect for the database
  • hibernate.show_sql: Whether to show the generated SQL statements
  • hibernate.hbm2ddl.auto: The strategy for automatically creating or updating the database schema
  • hibernate.cache.provider_class: The class name of the cache provider to use
  • hibernate.default_schema: The default database schema
  • hibernate.current_session_context_class: The class name of the current session context implementation

Follow-up 2

How does Hibernate use this file?

Hibernate uses the hibernate.cfg.xml file to configure the session factory, which is a central component in Hibernate. The session factory is responsible for creating and managing Hibernate sessions, and it uses the information provided in the hibernate.cfg.xml file to establish the database connection, load the mapping files, and set other configuration options.

Follow-up 3

Can you provide an example of a hibernate.cfg.xml file?

Sure! Here's an example of a hibernate.cfg.xml file:





        jdbc:mysql://localhost:3306/mydatabase
        root
        password
        org.hibernate.dialect.MySQLDialect
        true
        update


Follow-up 4

Is it possible to use Hibernate without a hibernate.cfg.xml file?

Yes, it is possible to use Hibernate without a hibernate.cfg.xml file. Instead of using a separate configuration file, you can configure Hibernate programmatically by creating an instance of org.hibernate.cfg.Configuration and setting the necessary properties directly on it. Here's an example:

Configuration configuration = new Configuration();
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/mydatabase");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "password");
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");

SessionFactory sessionFactory = configuration.buildSessionFactory();

3. How can you specify mapping resources in Hibernate?

In Hibernate 6.x with Spring Boot 3.x, mapping resources are specified almost exclusively through annotations on entity classes. XML mapping files (hbm.xml) still exist but are deprecated in Hibernate 6 and rarely used in new projects.

Annotation-based mapping (current standard)

Annotate each entity with @Entity from jakarta.persistence. Spring Boot's auto-configuration scans the package tree of the main class and registers all annotated types automatically:

import jakarta.persistence.*;

@Entity
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String description;
}

To control which packages are scanned, add @EntityScan to a configuration class:

@SpringBootApplication
@EntityScan("com.example.domain")
public class App { ... }

Explicit registration via LocalContainerEntityManagerFactoryBean

When configuring JPA manually (no Spring Boot auto-config), specify packages directly:

factory.setPackagesToScan("com.example.domain");

XML mapping files (legacy)

For legacy hbm.xml-based projects, register files through LocalSessionFactoryBean:

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
    sf.setMappingResources("mappings/Order.hbm.xml");
    return sf;
}

Or via hibernate.cfg.xml:


Key interview gotchas

  • All JPA annotations must import from jakarta.persistence, not javax.persistence — this changed with Jakarta EE 9 and Spring Boot 3.
  • hbm.xml support is deprecated in Hibernate 6 and will be removed in a future major version.
  • @EntityScan and @ComponentScan are distinct — forgetting @EntityScan when entities live in a separate module is a common production bug.
  • Mixing annotation and XML mapping for the same entity causes conflicts and should be avoided.
↑ Back to top

Follow-up 1

What is the purpose of mapping resources?

The purpose of mapping resources in Hibernate is to define the mapping between Java classes and database tables. This mapping allows Hibernate to automatically generate SQL statements and perform CRUD (Create, Read, Update, Delete) operations on the database based on the defined mappings.

Follow-up 2

Can you provide an example of a mapping resource?

Sure! Here's an example of a mapping resource in Hibernate using XML configuration:










In this example, the mapping resource defines the mapping between the User class and the users table in the database. It specifies the primary key (id) and the properties (name and email) of the User class.

Follow-up 3

How do you specify mapping resources in the hibernate.cfg.xml file?

To specify mapping resources in the hibernate.cfg.xml file, you can use the element. This element should be placed inside the element. Here's an example:







In this example, the mapping resource com/example/User.hbm.xml is specified in the hibernate.cfg.xml file.

Follow-up 4

What happens if a mapping resource is not found or is incorrect?

If a mapping resource is not found or is incorrect, Hibernate will throw an exception during the configuration or session factory creation process. This exception will indicate that the mapping resource could not be loaded or parsed correctly. It is important to ensure that the mapping resources are correctly specified and accessible in order to avoid such exceptions.

4. What is the purpose of the SessionFactory in Hibernate?

The SessionFactory is the central, heavyweight object in Hibernate's architecture. It is created once at application startup and shared across all threads for the lifetime of the application.

Primary responsibilities

  • Session creation: acts as a factory for Session instances, each of which represents a single unit of work (a database conversation).
  • Second-level cache host: the SessionFactory owns the second-level cache (e.g., Ehcache, Caffeine, Infinispan). Data cached at this level survives individual sessions.
  • Compiled mapping metadata: all entity mappings, SQL generation, and type resolution are resolved and compiled when the SessionFactory is built — this is why construction is expensive.
  • Connection pool reference: it holds a reference to the configured connection pool and delegates connection acquisition to ConnectionProvider.

SessionFactory vs EntityManagerFactory

In modern JPA-based applications (jakarta.persistence), you work with EntityManagerFactory, which is the JPA equivalent. Hibernate's SessionFactory extends EntityManagerFactory, so either API can be used:

// Pure JPA (preferred with Spring Boot 3)
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-pu");
EntityManager em = emf.createEntityManager();

// Hibernate-native (unwrap when you need Hibernate-specific features)
SessionFactory sf = emf.unwrap(SessionFactory.class);
Session session = sf.openSession();

Spring Boot context

In a Spring Boot 3 application, SessionFactory / EntityManagerFactory is created and managed automatically by HibernateJpaAutoConfiguration. You never build it manually in typical setups:

@Autowired
private EntityManagerFactory emf;  // injected by Spring

If you need the native SessionFactory:

SessionFactory sf = emf.unwrap(SessionFactory.class);

Key interview gotchas

  • SessionFactory is thread-safe and expensive to create; Session is not thread-safe and is cheap.
  • Creating a new SessionFactory per request is a classic performance anti-pattern.
  • In Hibernate 6, the Configuration bootstrapping API changed — the preferred approach uses StandardServiceRegistryBuilder or Spring's LocalSessionFactoryBean.
  • The second-level cache is disabled by default and must be explicitly enabled via hibernate.cache.use_second_level_cache=true.
↑ Back to top

Follow-up 1

How do you create a SessionFactory?

To create a SessionFactory in Hibernate, you need to first create a Configuration object. The Configuration object is used to configure Hibernate and specify the database connection details, mapping files, and other settings. Once the Configuration object is configured, you can call its buildSessionFactory() method to create the SessionFactory.

Follow-up 2

What role does the Configuration object play in creating a SessionFactory?

The Configuration object in Hibernate is used to configure Hibernate and specify the database connection details, mapping files, and other settings. It is responsible for reading the configuration information from the hibernate.cfg.xml file or programmatically setting the configuration properties. The Configuration object is used to create the SessionFactory by calling its buildSessionFactory() method.

Follow-up 3

Can you have multiple SessionFactory instances in a Hibernate application?

Yes, it is possible to have multiple SessionFactory instances in a Hibernate application. Each SessionFactory represents a separate database connection and set of mappings. This can be useful in scenarios where you need to connect to multiple databases or have different configurations for different parts of your application.

Follow-up 4

What happens when you close a SessionFactory?

When you close a SessionFactory in Hibernate, it releases all the resources associated with it, including database connections and caches. It is important to close the SessionFactory when it is no longer needed to free up system resources. Once a SessionFactory is closed, you cannot create new sessions from it.

5. How can you configure Hibernate to use a connection pool?

Hibernate does not include a production-grade connection pool by default (it ships with a minimal built-in pool for testing only). In real applications you integrate an external pool — HikariCP, Apache DBCP2, or c3p0 — with Hibernate either through Spring Boot auto-configuration or manual configuration.

Spring Boot 3 (recommended approach)

Spring Boot auto-configures HikariCP when it is on the classpath (it is the default pool in spring-boot-starter-data-jpa). Configure pool properties in application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=user
spring.datasource.password=secret
spring.datasource.driver-class-name=org.postgresql.Driver

# HikariCP pool tuning
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.max-lifetime=1800000

Spring Boot wires the DataSource into the EntityManagerFactory automatically.

Manual Hibernate configuration (without Spring Boot)

Pass pool properties via hibernate.cfg.xml or programmatically. With HikariCP:

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/mydb");
config.setUsername("user");
config.setPassword("secret");
config.setMaximumPoolSize(20);
HikariDataSource ds = new HikariDataSource(config);

StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
    .applySetting(AvailableSettings.DATASOURCE, ds)
    .build();

SessionFactory sf = new MetadataSources(registry)
    .addAnnotatedClass(Order.class)
    .buildMetadata()
    .buildSessionFactory();

Key pool properties to know for interviews

Property Purpose
maximum-pool-size Upper bound on active connections
minimum-idle Connections kept warm when idle
connection-timeout Max wait to acquire a connection
idle-timeout How long idle connections are kept
max-lifetime Connection max age (must be < DB timeout)

Key interview gotchas

  • Hibernate's built-in pool (hibernate.connection.pool_size) is documented as not suitable for production use.
  • max-lifetime should always be shorter than the database's wait_timeout (MySQL) or tcp_keepalives_idle to avoid stale connections.
  • With Spring Boot, do not set both spring.datasource.* and raw hibernate.connection.* properties — they conflict.
  • Connection pool exhaustion under load surfaces as SQLTimeoutException / Connection is not available — a common production issue interviewers ask about.
↑ Back to top

Follow-up 1

What is a connection pool?

A connection pool is a cache of database connections maintained so that the connections can be reused when needed. It helps in reducing the overhead of creating a new connection for every database operation and improves the performance of the application.

Follow-up 2

Why would you want to use a connection pool?

Using a connection pool in Hibernate offers several benefits:

  1. Improved performance: Connection pooling allows reusing existing connections, which eliminates the overhead of creating a new connection for every database operation.
  2. Resource management: Connection pooling helps in managing database connections efficiently by limiting the number of connections and reusing them when needed.
  3. Scalability: Connection pooling enables handling multiple concurrent database requests by efficiently managing and reusing connections.
  4. Connection reuse: With connection pooling, connections can be reused across multiple database operations, reducing the time spent on establishing a new connection each time.

Follow-up 3

What are some of the connection pool properties you can set in the hibernate.cfg.xml file?

Some of the connection pool properties that can be set in the hibernate.cfg.xml file include:

  1. hibernate.connection.url: The JDBC URL of the database.
  2. hibernate.connection.username: The username for connecting to the database.
  3. hibernate.connection.password: The password for connecting to the database.
  4. hibernate.connection.pool_size: The maximum number of connections in the pool.
  5. hibernate.connection.min_pool_size: The minimum number of idle connections in the pool.
  6. hibernate.connection.max_pool_size: The maximum number of connections that can be created in the pool.
  7. hibernate.connection.timeout: The maximum time in seconds to wait for a connection from the pool.
  8. hibernate.connection.provider_class: The class name of the connection provider.

Follow-up 4

Can you provide an example of configuring a connection pool in Hibernate?

Sure! Here's an example of configuring a connection pool in Hibernate using the hibernate.cfg.xml file:




        jdbc:mysql://localhost:3306/mydatabase
        root
        password
        10
        5
        20
        30
        org.hibernate.connection.C3P0ConnectionProvider


Live mock interview

Mock interview: Configuration Management

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.

Next lesson Hibernate Dialects →