IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Hibernate Java Discussion :

Hibernate.cfg et multiple <session-factory>


Sujet :

Hibernate Java

  1. #1
    Membre éclairé
    Homme Profil pro
    Inscrit en
    Avril 2005
    Messages
    277
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39

    Informations forums :
    Inscription : Avril 2005
    Messages : 277
    Par défaut Hibernate.cfg et multiple <session-factory>
    Bonjour,

    Je cherche à améliorer mon HibernateFactory afin de gérer des sources de données différentes au sein d'un même fichier de conf !

    J'ai donc un fichier hibernate.cfg comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    <hibernate-configuration>
    	<session-factory name="CONFIG_1">
    		<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    		<property name="hibernate.connection.url">jdbc:postgresql://monserveur/maBase</property>
    		<property name="hibernate.connection.username">postgres</property>
    		<property name="hibernate.connection.password">monPassword</property>
    		<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    		<property name="hibernate.jdbc.batch_size">20</property>
    		<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    		<property name="show_sql">false</property>
     
    		<mapping class="com.monpackage.MaClasse" />
    	</session-factory>
     
    	<session-factory name="CONFIG_2">
    		<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    		<property name="hibernate.connection.url">jdbc:postgresql://monserveur/maBase2</property>
    		<property name="hibernate.connection.username">postgres</property>
    		<property name="hibernate.connection.password">monPassword</property>
    		<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    		<property name="hibernate.jdbc.batch_size">20</property>
    		<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    		<property name="show_sql">false</property>
     
    		<mapping class="com.monpackage.MonAutreClasse" />
    	</session-factory>
    </hibernate-configuration>
    Je voudrais que mon HibernateFactory prenne en paramètre le "NAME" du noeud "session-factory" pour récupèrer la bonne connexion.

    J'ai donc aussi une classe AbstractDAO :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    public abstract class AbstractDao<T>
    {
    	private Session		session;
    	private Transaction	tx;
     
    	private Class<T>	clazz;
     
    	public AbstractDao(Class<T> clazz)
    	{
    		this.clazz = clazz;
    		init();
    	}
     
    	private void init()
    	{
    		HibernateFactory.buildIfNeeded();
    	}
     
    	protected void saveOrUpdate(T obj)
    	{
    		try
    		{
    			startOperation();
    			session.saveOrUpdate(obj);
    			tx.commit();
    		} catch (HibernateException e)
    		{
    			handleException(e);
    		} finally
    		{
    			HibernateFactory.close(session);
    		}
    	}
     
    	protected void delete(T obj)
    	{
    		try
    		{
    			startOperation();
    			session.delete(obj);
    			tx.commit();
    		} catch (HibernateException e)
    		{
    			handleException(e);
    		} finally
    		{
    			HibernateFactory.close(session);
    		}
    	}
     
    	@SuppressWarnings("unchecked")
    	public T find(Serializable id)
    	{
    		T obj = null;
    		try
    		{
    			startOperation();
    			obj = (T) session.load(clazz, id);
    			tx.commit();
    		} catch (HibernateException e)
    		{
    			handleException(e);
    		} finally
    		{
    			HibernateFactory.close(session);
    		}
    		return obj;
    	}
     
    	@SuppressWarnings("unchecked")
    	public List<T> findAll()
    	{
    		List<T> objects = new ArrayList<T>(0);
    		try
    		{
    			startOperation();
    			Query query = session.createQuery("from " + clazz.getName());
    			objects = (List<T>) query.list();
    			tx.commit();
    		} catch (HibernateException e)
    		{
    			handleException(e);
    		} finally
    		{
    			HibernateFactory.close(session);
    		}
    		return objects;
    	}
     
    	@SuppressWarnings("unchecked")
    	public List<T> findAll(String property, Object value)
    	{
    		List<T> objects = new ArrayList<T>(0);
    		try
    		{
    			startOperation();
    			Query query = session.createQuery("from " + clazz.getName() + " where " + property + " = '" + value.toString() + "'");
    			objects = (List<T>) query.list();
    			tx.commit();
    		} catch (HibernateException e)
    		{
    			handleException(e);
    		} finally
    		{
    			HibernateFactory.close(session);
    		}
    		return objects;
    	}
     
    	protected void handleException(HibernateException e) throws HibernateException
    	{
    		HibernateFactory.rollback(tx);
    		e.printStackTrace();
    	}
     
    	private void startOperation() throws HibernateException
    	{
    		session = HibernateFactory.openSession();
    		tx = session.beginTransaction();
    	}
    }
    Cette classe permet de la DAO de façon vraiment primaire ...

    Voila mon HibernateFactory :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    public class HibernateFactory
    {
    	private static SessionFactory	sessionFactory;
     
    	/**
             * @return
             * @throws DataAccessLayerException
             */
    	public static void buildIfNeeded() throws HibernateException
    	{
    		if (sessionFactory == null)
    		{
    			try
    			{
    				AnnotationConfiguration configuration = new AnnotationConfiguration();
    				sessionFactory = configuration.configure().buildSessionFactory();
    			} catch (HibernateException e)
    			{
    				throw e;
    			}
    		}
    	}
     
    	/**
             * @return
             */
    	public static SessionFactory getSessionFactory()
    	{
    		return sessionFactory;
    	}
     
    	/**
             * @return
             * @throws HibernateException
             */
    	public static Session openSession() throws HibernateException
    	{
    		buildIfNeeded();
    		return sessionFactory.openSession();
    	}
     
    	/**
             * 
             */
    	public static void closeFactory()
    	{
    		if (sessionFactory != null)
    		{
    			try
    			{
    				sessionFactory.close();
    			} catch (HibernateException ignored)
    			{
    				System.err.println("Couldn't close SessionFactory");
    			}
    		}
    	}
     
    	/**
             * @param session
             */
    	public static void close(Session session)
    	{
    		if (session != null)
    		{
    			try
    			{
    				session.close();
    			} catch (HibernateException ignored)
    			{
    				System.err.println("Couldn't close Session");
    			}
    		}
    	}
     
    	/**
             * @param tx
             */
    	public static void rollback(Transaction tx)
    	{
    		try
    		{
    			if (tx != null)
    				tx.rollback();
    		} catch (HibernateException ignored)
    		{
    			System.err.println("Couldn't rollback Transaction");
    		}
    	}
    }
    Donc maintenant je voudrais que mon HibernateFactory puisse lors de "l'openSession" prendre une chaine en paramètre.

    Par exemple, dans mon DAO pour mon objet "MaClasse", je ferais un , permettant donc de bien manipuler l'objet sur la bonne connexion.

    Merci pour votre aide ...

  2. #2
    Expert confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Par défaut
    Shards peut être?

  3. #3
    Membre Expert
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 277
    Par défaut
    Tu pourrais aussi faire un deuxième fichier de conf, et choisir lequel tu charges par la méthode doConfigure(InputStream stream, String resourceName) de la classe Configuration.
    Il y a peut-être la possibilité de garder un seul fichier, mais je n'ai pas creusé plus loin.

  4. #4
    Membre éclairé
    Homme Profil pro
    Inscrit en
    Avril 2005
    Messages
    277
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39

    Informations forums :
    Inscription : Avril 2005
    Messages : 277
    Par défaut
    "Shards" devrait fonctionner, mais apparement pas trop évident à utiliser, et peut être un peu trop complexe pour mon très simple besoin ...

    Sinon oui j'ai pensé à charger des fichiers différents, mais c'est moins propre et plus difficile à gérer ...
    Du XML avec différents noeuds devrait permettre ça simplement je pense ...

    Je continue à creuser, mais je suis sur qu'Hibernate le permet ...

Discussions similaires

  1. Réponses: 5
    Dernier message: 26/10/2010, 17h44
  2. [tomcat 5.5,hibernate 3.2] bind entre la session factory et jndi
    Par sallemel dans le forum Tomcat et TomEE
    Réponses: 1
    Dernier message: 19/08/2010, 21h43
  3. [HIBERNATE] Error getting Hibernate Session Factory
    Par so7lob dans le forum Hibernate
    Réponses: 1
    Dernier message: 16/12/2008, 14h29
  4. hibernate et session factory
    Par sandytarit dans le forum Eclipse Java
    Réponses: 2
    Dernier message: 17/01/2007, 13h10
  5. [Hibernate] Session Factory ThreadSafe
    Par K-Kaï dans le forum Hibernate
    Réponses: 6
    Dernier message: 03/07/2006, 10h55

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo