Ce contenu n'est pas disponible dans la langue sélectionnée.
Chapter 3. Configuration
Hibernate is designed to operate in many different environments and, as such, there is a broad range of configuration parameters. Fortunately, most have sensible default values and Hibernate is distributed with an example
hibernate.properties file in etc/ that displays the various options. Simply put the example file in your classpath and customize it to suit your needs.
3.1. Programmatic configuration Copier lienLien copié sur presse-papiers!
Copier lienLien copié sur presse-papiers!
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()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
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 file names.
A
org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:
This is not the only way to pass configuration properties to Hibernate. Some alternative options include:
- Pass an instance of
java.util.PropertiestoConfiguration.setProperties(). - Place a file named
hibernate.propertiesin a root directory of the classpath. - Set
Systemproperties usingjava -Dproperty=value. - Include
<property>elements inhibernate.cfg.xml(this is discussed later).
If you want to get started quickly
hibernate.properties is the easiest approach.
The
org.hibernate.cfg.Configuration is intended as a start up object that will be discarded once a SessionFactory is created.