Programmatic configuration in Hibernate

By: Felix Viewed: 153399 times  Printer Friendly Format    

An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The org.hibernate.cfg.Configuration is used to build an immutable org.hibernate.SessionFactory. The mappings are compiled from various XML mapping files.

You can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:

Configuration cfg = new Configuration()

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:

Configuration cfg = new Configuration()

Hibernate will then search for mapping files named /org/hibernate/auction/Item.hbm.xml and /org/hibernate/auction/Bid.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.

A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:

Configuration cfg = new Configuration()
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
.setProperty("hibernate.order_updates", "true");

This is not the only way to pass configuration properties to Hibernate. Some alternative options include:

  1. Pass an instance of java.util.Properties to Configuration.setProperties().
  2. Place a file named in a root directory of the classpath.
  3. Set System properties using java -Dproperty=value.
  4. Include <property> elements in hibernate.cfg.xml.

If you want to get started quickly is the easiest approach.

The org.hibernate.cfg.Configuration is intended as a startup-time object that will be discarded once a SessionFactory is created.

Most Viewed Articles (in Hibernate )

Latest Articles (in Hibernate)

Comment on this tutorial