CHAPTER 2 Starting a project Building a SessionFactory (Web site template)

CHAPTER 2 Starting a project Building a SessionFactory This is an example of a typical Hibernate startup procedure, in one line of code, using automatic configuration file detection: SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Wait how did Hibernate know where the configuration file was located and which one to load? When new Configuration() is called, Hibernate searches for a file named hibernate.properties in the root of the classpath. If it s found, all hibernate.* properties are loaded and added to the Configuration object. When configure() is called, Hibernate searches for a file named hibernate.cfg.xml in the root of the classpath, and an exception is thrown if it can t be found. You don t have to call this method if you don t have this configuration file, of course. If settings in the XML configuration file are duplicates of properties set earlier, the XML settings override the previous ones. The location of the hibernate.properties configuration file is always the root of the classpath, outside of any package. If you wish to use a different file or to have Hibernate look in a subdirectory of your classpath for the XML configuration file, you must pass a path as an argument of the configure() method: SessionFactory sessionFactory = new Configuration() .configure(”/persistence/auction.cfg.xml”) .buildSessionFactory(); Finally, you can always set additional configuration options or mapping file locations on the Configuration object programmatically, before building the SessionFactory: SessionFactory sessionFactory = new Configuration() .configure(”/persistence/auction.cfg.xml”) .setProperty(Environment.DEFAULT_SCHEMA, “CAVEATEMPTOR”) .addResource(”auction/CreditCard.hbm.xml”) .buildSessionFactory(); Many sources for the configuration are applied here: First the hibernate.properties file in your classpath is read (if present). Next, all settings from /persistence/ auction.cfg.xml are added and override any previously applied settings. Finally, an additional configuration property (a default database schema name) is set programmatically, and an additional Hibernate XML mapping metadata file is added to the configuration. You can, of course, set all options programmatically, or switch between different XML configuration files for different deployment databases. There is effectively no
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.