Programming Tutorials

Programmatic configuration in Hibernate

By: Felix in Hibernate Tutorials on 2022-12-29  

In Hibernate, programmatic configuration is an alternative approach to XML configuration. It involves creating a configuration object and setting its properties programmatically instead of configuring them in an XML file.

Here are the steps to perform programmatic configuration in Hibernate:

Create a Configuration object:

Configuration configuration = new Configuration();

Set the properties of the Configuration object:

configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/mydatabase");
configuration.setProperty("hibernate.connection.username", "myusername");
configuration.setProperty("hibernate.connection.password", "mypassword");
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("", "update");

These properties include the JDBC driver class, database connection URL, username, password, dialect, and property that specifies how Hibernate should handle database schema changes.

Use the Configuration object to create a SessionFactory object:

SessionFactory sessionFactory = configuration.buildSessionFactory();

Open a session from the SessionFactory object:

Session session = sessionFactory.openSession();

Use the session to perform database operations:

Transaction transaction = session.beginTransaction();
// Perform database operations here

Here, we create a transaction and use it to perform database operations.

Close the session:


Close the SessionFactory object:


This is the final step and should be done when the application is shutting down.

Overall, programmatic configuration offers more flexibility than XML configuration and allows you to create a Hibernate configuration dynamically at runtime.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Hibernate )

Latest Articles (in Hibernate)