openSession :- When you call SessionFactory.openSession, it always create new Session object afresh and give it to you.
È necessario in modo esplicito a filo e chiudere questi oggetti di sessione. Poiché gli oggetti di sessione non sono thread-safe, è necessario creare un oggetto sessione per richiesta in ambiente multithread e una sessione per richiesta anche nelle applicazioni Web.
getCurrentSession :- When you call SessionFactory. getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.
When you call SessionFactory. getCurrentSession , it creates a new Session if not exists , else use same session which is in current hibernate context. It automatically flush and close session when transaction ends, so you do not need to do externally.
If you are using hibernate in single threaded environment , you can use getCurrentSession, as it is faster in performance as compare to creating new session each time.
You need to add following property to hibernate.cfg.xml to use getCurrentSession method.
<session-factory>
<!-- Put other elements here -->
<property name="hibernate.current_session_context_class">
thread
</property>
</session-factory>
fonte
2017-08-17 11:22:30
Grazie mille, @gkamal. Osservo il codice in [Open Session in View] (http://community.jboss.org/wiki/OpenSessionInView) del documento. (Il tuo link rimanda a quei documenti.) L'autore suggerisce l'uso del filtro. Nel suo codice di filtro, non chiama 'openSession()' o 'close()'. Chiama solo 'getCurrentSession()'. Immagino che abbia impostato 'current_session_context' su' thread'. Ora penso di capire 'getCurrentSession()'. Tuttavia, non so quando dovrei usare 'openSession()'. – wannik
Utilizzerai OpenSession se non desideri che la sessione sia associata a qualsiasi contesto. Vi sono alcune situazioni in cui è necessaria una sessione diversa, diversa da quella vincolata al contesto (gli Hibernate Interceptors hanno una limitazione che non è possibile utilizzare la sessione originale): in questi casi si utilizzerà OpenSession anziché currentSession. OpenSession crea una nuova sessione che devi chiudere esplicitamente. Ad esempio, in un metodo DAO chiamerai OpenSession: usa la sessione e chiudila. – gkamal
am usando getCurrentSession(); perché l'ho inizializzato in listener non filtro è ok dal tuo punto di vista; sto usando mvc2 servlet jsp – shareef