Java.Hibernate.Beginner.What is the purpose of hibernate.properties?

hibernate.properties is an alternative configuration file for Hibernate where you can specify key-value pairs of Hibernate settings, like database connection details and other properties — similar to what you’d define in hibernate.cfg.xml, but in a simpler .properties format.


🔹 What is it used for?

  • Provides a way to configure Hibernate without XML.
  • Useful in standalone Java SE apps or frameworks where you prefer properties files.
  • Hibernate looks for hibernate.properties automatically on the classpath (e.g., src/main/resources).

🔹 Example hibernate.properties:

hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/mydb
hibernate.connection.username=root
hibernate.connection.password=secret

hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

🔹 How does Hibernate use it?
When you build a Configuration object without explicitly specifying settings, Hibernate automatically looks for a hibernate.properties file on the classpath and loads it:

Configuration config = new Configuration();
config.configure(); // loads hibernate.cfg.xml if present
// BUT: even without XML, Hibernate will load hibernate.properties if found on classpath

SessionFactory sessionFactory = config.buildSessionFactory();

🔹 Difference from hibernate.cfg.xml:
hibernate.cfg.xml supports both settings and entity mappings.
hibernate.properties supports settings only, not entity mappings — you still need to programmatically add mappings if you don’t use annotations.

🔹 Modern apps (e.g., Spring Boot):
You don’t typically use hibernate.properties, since application.properties or application.yml replaces its role.

Key takeaway:
hibernate.properties provides a simple, XML-free way to configure Hibernate using a flat properties file — best suited for standalone Hibernate setups or legacy apps.

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