Hibernate - getCurrentSession - get invalid with no active transaction

I am testing hibernate 4.1.9 using java command line application. I configured the current session context on the thread:

<property name="hibernate.current_session_context_class">thread</property> 

But when I call sessionFactory.getCurrentSession() , it throws an exception:

 Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348) at com.sun.proxy.$Proxy9.get(Unknown Source) .... 

I can use openSession , and it doesn't matter (this is a test after all). I'm just wondering why I can't get the getCurrentSession method getCurrentSession work as advertised.

Thanks.

+4
source share
2 answers

The first call to sessionFactory.getCurrentSession () returns a new session. The problem was in my configuration.

I had it like this:

 <property name="hibernate.current_session_context_class">thread</property> 

After changing this parameter, it worked:

 <property name="current_session_context_class">thread</property> 
+2
source

This is a little old question, but he thought about answering correctly.

Changing the property name hibernate.current_session_context_class to current_session_context_class , force the default JTASessionContext .

Below is a snippet from hibernate SessionFactoryImpl . BTW, Environment.CURRENT_SESSION_CONTEXT_CLASS - "hibernate.current_session_context_class" . ThreadLocalSessionContext causes this problem.

 private CurrentSessionContext buildCurrentSessionContext() { String impl = (String) properties.get( Environment.CURRENT_SESSION_CONTEXT_CLASS ); // for backward-compatibility if ( impl == null ) { if ( canAccessTransactionManager() ) { impl = "jta"; } else { return null; } } if ( "jta".equals( impl ) ) { // if ( ! transactionFactory().compatibleWithJtaSynchronization() ) { // LOG.autoFlushWillNotWork(); // } return new JTASessionContext( this ); } else if ( "thread".equals( impl ) ) { return new ThreadLocalSessionContext( this ); } else if ( "managed".equals( impl ) ) { return new ManagedSessionContext( this ); } else { try { Class implClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( impl ); return (CurrentSessionContext) implClass.getConstructor( new Class[] { SessionFactoryImplementor.class } ) .newInstance( this ); } catch( Throwable t ) { LOG.unableToConstructCurrentSessionContext( impl, t ); return null; } } } 

Please check ThreadLocalSessionContext.TransactionProtectionWrapper.invoke

0
source

All Articles