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/Spring : gestion des sessions


Sujet :

Hibernate Java

  1. #1
    Membre expérimenté Avatar de herve91
    Profil pro
    Inscrit en
    Novembre 2004
    Messages
    1 282
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2004
    Messages : 1 282
    Points : 1 608
    Points
    1 608
    Par défaut Hibernate/Spring : gestion des sessions
    J'ai défini la classe suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    class DaoImpl extends HibernateDaoSupport {
     
    	protected Session currentSession() {
    		return getHibernateTemplate().getSessionFactory().getCurrentSession();
    	}
    }
    La configuration Spring est la suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
        <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
            <property name="cacheQueries">
                <value>true</value>
            </property>
        </bean>
     
        <!-- This is the base definition for all Hibernate based DAOs -->
        <bean id="hibernateDaoSupport" 
              class="org.springframework.orm.hibernate3.support.HibernateDaoSupport"
              abstract="true">
        </bean>
    A l'exécution, j'obtiens l'exception suivante :
    org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean$TransactionAwareInvocationHandler.invoke(AbstractSessionFactoryBean.java:300)
    at $Proxy0.getCurrentSession(Unknown Source)
    at monpacakge.DaoImpl.currentSession(DaoImpl.java:41)
    Merci de votre aide

  2. #2
    Membre régulier
    Profil pro
    Inscrit en
    Novembre 2009
    Messages
    82
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2009
    Messages : 82
    Points : 82
    Points
    82
    Par défaut
    Salut,

    oulà!
    Qu'est ce que tu essayes de faire au juste ?
    Quelle est ton code pour utiliser ton DaoImpl ?

    Code Poet

  3. #3
    Membre du Club
    Inscrit en
    Février 2010
    Messages
    66
    Détails du profil
    Informations forums :
    Inscription : Février 2010
    Messages : 66
    Points : 47
    Points
    47
    Par défaut
    DAOImpl contient tes méthodes de persistance avec cette déclaration au début
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    private HibernateTemplate hibernateTemplate;
     
    	public void setSessionFactory(SessionFactory sessionFactory) {
     
    		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    	}
    par exemple
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    public void createEmploye(Employes employe) {
     
    		hibernateTemplate.saveOrUpdate(employe);
    	}

  4. #4
    Membre régulier
    Profil pro
    Inscrit en
    Novembre 2009
    Messages
    82
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2009
    Messages : 82
    Points : 82
    Points
    82
    Par défaut
    Pourquoi tu redéfinies ce que fait HibernateDaoSupport.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    private HibernateTemplate hibernateTemplate;
     
    public void setSessionFactory(SessionFactory sessionFactory) {
    	this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    La source de HibernateDaoSupport :
    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
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
     
    /*
     * Copyright 2002-2008 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
     
    package org.springframework.orm.hibernate3.support;
     
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
     
    import org.springframework.dao.DataAccessException;
    import org.springframework.dao.DataAccessResourceFailureException;
    import org.springframework.dao.support.DaoSupport;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.orm.hibernate3.SessionFactoryUtils;
     
    /**
     * Convenient super class for Hibernate-based data access objects.
     *
     * <p>Requires a {@link org.hibernate.SessionFactory} to be set, providing a
     * {@link org.springframework.orm.hibernate3.HibernateTemplate} based on it to
     * subclasses through the {@link #getHibernateTemplate()} method.
     * Can alternatively be initialized directly with a HibernateTemplate,
     * in order to reuse the latter's settings such as the SessionFactory,
     * exception translator, flush mode, etc.
     *
     * <p>This base class is mainly intended for HibernateTemplate usage but can
     * also be used when working with a Hibernate Session directly, for example
     * when relying on transactional Sessions. Convenience {@link #getSession}
     * and {@link #releaseSession} methods are provided for that usage style.
     *
     * <p>This class will create its own HibernateTemplate instance if a SessionFactory
     * is passed in. The "allowCreate" flag on that HibernateTemplate will be "true"
     * by default. A custom HibernateTemplate instance can be used through overriding
     * {@link #createHibernateTemplate}.
     *
     * @author Juergen Hoeller
     * @since 1.2
     * @see #setSessionFactory
     * @see #getHibernateTemplate
     * @see org.springframework.orm.hibernate3.HibernateTemplate
     */
    public abstract class HibernateDaoSupport extends DaoSupport {
     
    	private HibernateTemplate hibernateTemplate;
     
     
    	/**
             * Set the Hibernate SessionFactory to be used by this DAO.
             * Will automatically create a HibernateTemplate for the given SessionFactory.
             * @see #createHibernateTemplate
             * @see #setHibernateTemplate
             */
    	public final void setSessionFactory(SessionFactory sessionFactory) {
    		if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
    			this.hibernateTemplate = createHibernateTemplate(sessionFactory);
    		}
    	}
     
    	/**
             * Create a HibernateTemplate for the given SessionFactory.
             * Only invoked if populating the DAO with a SessionFactory reference!
             * <p>Can be overridden in subclasses to provide a HibernateTemplate instance
             * with different configuration, or a custom HibernateTemplate subclass.
             * @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for
             * @return the new HibernateTemplate instance
             * @see #setSessionFactory
             */
    	protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
    		return new HibernateTemplate(sessionFactory);
    	}
     
    	/**
             * Return the Hibernate SessionFactory used by this DAO.
             */
    	public final SessionFactory getSessionFactory() {
    		return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
    	}
     
    	/**
             * Set the HibernateTemplate for this DAO explicitly,
             * as an alternative to specifying a SessionFactory.
             * @see #setSessionFactory
             */
    	public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    		this.hibernateTemplate = hibernateTemplate;
    	}
     
    	/**
             * Return the HibernateTemplate for this DAO,
             * pre-initialized with the SessionFactory or set explicitly.
             * <p><b>Note: The returned HibernateTemplate is a shared instance.</b>
             * You may introspect its configuration, but not modify the configuration
             * (other than from within an {@link #initDao} implementation).
             * Consider creating a custom HibernateTemplate instance via
             * <code>new HibernateTemplate(getSessionFactory())</code>, in which
             * case you're allowed to customize the settings on the resulting instance.
             */
    	public final HibernateTemplate getHibernateTemplate() {
    	  return this.hibernateTemplate;
    	}
     
    	protected final void checkDaoConfig() {
    		if (this.hibernateTemplate == null) {
    			throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
    		}
    	}
     
     
    	/**
             * Obtain a Hibernate Session, either from the current transaction or
             * a new one. The latter is only allowed if the
             * {@link org.springframework.orm.hibernate3.HibernateTemplate#setAllowCreate "allowCreate"}
             * setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is "true".
             * <p><b>Note that this is not meant to be invoked from HibernateTemplate code
             * but rather just in plain Hibernate code.</b> Either rely on a thread-bound
             * Session or use it in combination with {@link #releaseSession}.
             * <p>In general, it is recommended to use HibernateTemplate, either with
             * the provided convenience operations or with a custom HibernateCallback
             * that provides you with a Session to work on. HibernateTemplate will care
             * for all resource management and for proper exception conversion.
             * @return the Hibernate Session
             * @throws DataAccessResourceFailureException if the Session couldn't be created
             * @throws IllegalStateException if no thread-bound Session found and allowCreate=false
             * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
             */
    	protected final Session getSession()
    	    throws DataAccessResourceFailureException, IllegalStateException {
     
    		return getSession(this.hibernateTemplate.isAllowCreate());
    	}
     
    	/**
             * Obtain a Hibernate Session, either from the current transaction or
             * a new one. The latter is only allowed if "allowCreate" is true.
             * <p><b>Note that this is not meant to be invoked from HibernateTemplate code
             * but rather just in plain Hibernate code.</b> Either rely on a thread-bound
             * Session or use it in combination with {@link #releaseSession}.
             * <p>In general, it is recommended to use
             * {@link #getHibernateTemplate() HibernateTemplate}, either with
             * the provided convenience operations or with a custom
             * {@link org.springframework.orm.hibernate3.HibernateCallback} that
             * provides you with a Session to work on. HibernateTemplate will care
             * for all resource management and for proper exception conversion.
             * @param allowCreate if a non-transactional Session should be created when no
             * transactional Session can be found for the current thread
             * @return the Hibernate Session
             * @throws DataAccessResourceFailureException if the Session couldn't be created
             * @throws IllegalStateException if no thread-bound Session found and allowCreate=false
             * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
             */
    	protected final Session getSession(boolean allowCreate)
    	    throws DataAccessResourceFailureException, IllegalStateException {
     
    		return (!allowCreate ?
    		    SessionFactoryUtils.getSession(getSessionFactory(), false) :
    				SessionFactoryUtils.getSession(
    						getSessionFactory(),
    						this.hibernateTemplate.getEntityInterceptor(),
    						this.hibernateTemplate.getJdbcExceptionTranslator()));
    	}
     
    	/**
             * Convert the given HibernateException to an appropriate exception from the
             * <code>org.springframework.dao</code> hierarchy. Will automatically detect
             * wrapped SQLExceptions and convert them accordingly.
             * <p>Delegates to the
             * {@link org.springframework.orm.hibernate3.HibernateTemplate#convertHibernateAccessException}
             * method of this DAO's HibernateTemplate.
             * <p>Typically used in plain Hibernate code, in combination with
             * {@link #getSession} and {@link #releaseSession}.
             * @param ex HibernateException that occured
             * @return the corresponding DataAccessException instance
             * @see org.springframework.orm.hibernate3.SessionFactoryUtils#convertHibernateAccessException
             */
    	protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
    		return this.hibernateTemplate.convertHibernateAccessException(ex);
    	}
     
    	/**
             * Close the given Hibernate Session, created via this DAO's SessionFactory,
             * if it isn't bound to the thread (i.e. isn't a transactional Session).
             * <p>Typically used in plain Hibernate code, in combination with
             * {@link #getSession} and {@link #convertHibernateAccessException}.
             * @param session the Session to close
             * @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession
             */
    	protected final void releaseSession(Session session) {
    		SessionFactoryUtils.releaseSession(session, getSessionFactory());
    	}
     
    }

    J'ai pas très bien compris pourquoi tu choisis de redéfinir
    Code Poet

  5. #5
    Membre régulier
    Profil pro
    Inscrit en
    Novembre 2009
    Messages
    82
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2009
    Messages : 82
    Points : 82
    Points
    82
    Par défaut
    Si tu choisis d'utiliser HibernateDaoSupport alors le bean hibernateTemplate ne sert à rien.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    ...
    </bean>
    il faut juste utiliser :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    <!-- This is the base definition for all Hibernate based DAOs -->
    <bean id="daoImpl" 
          class="....DaoImpl" >
     
    <property name="sessionFactory">
    	<ref local="sessionFactory"/>
    </property>
     
    </bean>
    Tu crees une interface buisness.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    public interface EmployeBuisness {
     
    	public void createEmploye(Employes employe);
     
    }
    Ta class DaoImpl
    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
     
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
     
    class DaoImpl extends HibernateDaoSupport implements EmployeBuisness{
     
    	public DaoImpl(){
    		super();
    	}
     
    	public void createEmploye(Employes employe) {
    		super.getHibernateTemplate().saveOrUpdate(employe);
    	}
     
    }
    Utilisation dans un main :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
     
    /** Utilisation de Spring DAO Support pour configurer Hibernate **/
    		String configLocation = "classpath:hibernateBeanSpring.xml";
    		ClassPathXmlApplicationContext factory = new ClassPathXmlApplicationContext( configLocation );
     
    		Object bean = factory.getBean("daoImpl");
     
    		if( bean instanceof EmployeBuisness){
    			EmployeBuisness process = (EmployeBuisness) bean;
                            process.createEmploye( new Employes(...) );
                    }
    Il te faut définir une SessionFactory dans ton fichier de configuration Spring aussi. Je te laisse le faire
    Code Poet

  6. #6
    Membre régulier
    Profil pro
    Inscrit en
    Novembre 2009
    Messages
    82
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2009
    Messages : 82
    Points : 82
    Points
    82
    Par défaut
    Tape "bean id sessionfactory" dans go000ogle tu trouveras des exemples des différentes manières de créer la sessionfactory.

    Tchao bon courage
    Code Poet

Discussions similaires

  1. Gestion des session Spring Hibernate
    Par aminedeveloppement dans le forum Hibernate
    Réponses: 0
    Dernier message: 20/04/2013, 23h58
  2. [Spring & Hibernate] Gestion des sessions Hibernate
    Par Fennec. dans le forum Hibernate
    Réponses: 5
    Dernier message: 26/08/2010, 16h42
  3. Gestion des sessions Hibernate
    Par schumi2k2 dans le forum Hibernate
    Réponses: 5
    Dernier message: 31/03/2009, 17h44
  4. [Spring Security] Gestion des sessions concurrentes
    Par Shuret dans le forum Spring Web
    Réponses: 2
    Dernier message: 09/02/2009, 17h59
  5. Hibernate et la gestion des sessions
    Par ruff15 dans le forum Hibernate
    Réponses: 5
    Dernier message: 15/10/2008, 14h08

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