Chapitre 3. Configuration

Parce qu'Hibernate est conçu pour fonctionner dans différents environnements, il existe beaucoup de paramètres de configuration. Heureusement, la plupart ont des valeurs par défaut appropriées et la distribution d'Hibernate contient un exemple de fichier hibernate.properties dans le répertoire etc/ qui montre les différentes options. Vous n'avez qu'à placer ce fichier dans votre classpath et à l'adapter.

3.1. Configuration par programmation

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 may 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():

Configuration cfg = new Configuration()
    .addResource("Item.hbm.xml")
    .addResource("Bid.hbm.xml");

Une alternative (parfois meilleure) est de spécifier les classes mappées et de laisser Hibernate trouver les documents de mapping pour vous :

Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class);

Then Hibernate will look 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:

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

Ce n'est pas le seul moyen de passer des propriétés de configuration à Hibernate. Les différentes options sont :

  1. Pass an instance of java.util.Properties to Configuration.setProperties().

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

  3. Positionner les propriétés System en utilisant java -Dproperty=value.

  4. Inclure des éléments <property> dans le fichier hibernate.cfg.xml (voir plus loin).

hibernate.properties is the easiest approach if you want to get started quickly.

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