27. Legacy Bootstrapping

The legacy way to bootstrap a SessionFactory is via the org.hibernate.cfg.Configuration object. Configuration represents, essentially, a single point for specifying all aspects of building the SessionFactory: everything from settings, to mappings, to strategies, etc. I like to think of Configuration as a big pot to which we add a bunch of stuff (mappings, settings, etc) and from which we eventually get a SessionFactory.

There are some significant drawbacks to the legacy bootstrapping mechanism which led to its deprecation and the development of the new approach, which is discussed in Native Bootstrapping.

Configuration is semi-deprecated but still available for use, in a limited form that eliminates these drawbacks. “Under the covers”, Configuration uses the new bootstrapping code, so the things available there are also available here in terms of auto-discovery.

You can obtain the Configuration by instantiating it directly. You then specify mapping metadata (XML mapping documents, annotated classes) that describe your applications object model and its mapping to a SQL database.

  1. Configuration cfg = new Configuration()
  2. // addResource does a classpath resource lookup
  3. .addResource( "Item.hbm.xml" )
  4. .addResource( "Bid.hbm.xml" )
  5. // calls addResource using "/org/hibernate/auction/User.hbm.xml"
  6. .addClass( org.hibernate.auction.User.class )
  7. // parses Address class for mapping annotations
  8. .addAnnotatedClass( Address.class )
  9. // reads package-level (package-info.class) annotations in the named package
  10. .addPackage( "org.hibernate.auction" )
  11. .setProperty( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
  12. .setProperty( "hibernate.connection.datasource", "java:comp/env/jdbc/test" )
  13. .setProperty( "hibernate.order_updates", "true" );

There are other ways to specify Configuration information, including:

  • Place a file named hibernate.properties in a root directory of the classpath

  • Pass an instance of java.util.Properties to Configuration#setProperties

  • Via a hibernate.cfg.xml file

  • System properties using Java -Dproperty=value