Hibernate could not obtain transaction-synchronized Session for current thread on remote server
<p>I read the other answers on similar questions, but I haven't found a solution to my problem. I have a Tomcat7 server and a Spring application which uses Hibernate to connect to my PostgreSQL remote DB.</p>
<p>My framework versions are:<br />
Spring framework 4.2.2<br />
Spring security 3.2.5<br />
Hibernate 4.3.6</p>
<p>When I run my app on localhost everything is fine, but when I deploy it on my server I receive this error on login:</p>
<pre><code>org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
    org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
    org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    org.myapp.spring.dao.generic.GenericDAOImpl.getSession(GenericDAOImpl.java:59)
    org.myapp.spring.dao.impl.DeveloperDaoImpl.findByUsername(DeveloperDaoImpl.java:51)
    org.myapp.spring.service.impl.DeveloperServiceImpl.findByUsername(DeveloperServiceImpl.java:149)
    org.myapp.spring.web.security.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:23)
    org.myapp.spring.web.security.MyAuthenticationProvider.authenticate(MyAuthenticationProvider.java:30)
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
    org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
</code></pre>
<p>I have two initializer files:</p>
<pre><code>public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class&lt;?&gt;[] getRootConfigClasses() {
        Class[] config = {AppConfig.class};
        return config;
    }

    @Override
    protected Class&lt;?&gt;[] getServletConfigClasses() {
        Class[] config = {SecurityConfig.class, HibernateConfig.class};
        return config;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { &quot;/&quot; };
    }
</code></pre>
<p>and</p>
<pre><code>@Component
public class SecurityWebApplicationInizializer extends AbstractSecurityWebApplicationInitializer {
}
</code></pre>
<p>and three Config files:</p>
<pre><code>@EnableWebMvc
@ComponentScan({ &quot;org.myapp.spring.*&quot; })
@EnableTransactionManagement
@PropertySource(value=&quot;classpath:myapp.properties&quot;)
public class AppConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    @Autowired
    private TokenInterceptor tokenInterceptor;
    private ApplicationContext applicationContext;
    private static final String UTF8 = &quot;UTF-8&quot;;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor);
    }

//other methods
}
</code></pre>
<p>and</p>
<pre><code>@Configuration
@EnableWebSecurity
@EnableTransactionManagement
@ComponentScan(&quot;org.myapp.spring.web.security&quot;)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired private MyAuthenticationProvider authProvider;
@Autowired private UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider);
    auth.userDetailsService(userDetailsService);
}

@Override
public void configure(WebSecurity web) throws Exception {
    DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
    handler.setPermissionEvaluator(permissionEvaluator());
    web.expressionHandler(handler);
}

@Bean
public PermissionEvaluator permissionEvaluator() {
    return new MyPermissionEvaluator();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().and()
    .formLogin().loginPage(&quot;/html/login&quot;).defaultSuccessUrl(&quot;/html/index&quot;, true).permitAll()
    .and()
    .logout().logoutUrl(&quot;/html/logout&quot;).logoutSuccessUrl(&quot;/html/login?logout&quot;).invalidateHttpSession(true).clearAuthentication(true).permitAll()
    .and()
    .authorizeRequests()
    .antMatchers(&quot;/html/forbidden&quot;).permitAll()
    .antMatchers(&quot;/html/logistic&quot;).permitAll()
    .antMatchers(&quot;/html/ajax/logistic&quot;).permitAll()
    .antMatchers(&quot;/html/res/**&quot;).permitAll()
    .antMatchers(&quot;/html&quot;).authenticated()
    .antMatchers(&quot;/html/**&quot;).authenticated()
    .and()
    .exceptionHandling().accessDeniedPage(&quot;/html/forbidden&quot;);
}
}
</code></pre>
<p>and, finally:</p>
<pre><code>@Configuration
@EnableTransactionManagement
@ComponentScan({ &quot;org.myapp.spring.configuration&quot; })
@PropertySource(value = { &quot;classpath:hibernate.properties&quot; })
public class HibernateConfig {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean  sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { &quot;org.myapp.spring.model&quot;});
    sessionFactory.setHibernateProperties(hibernateProperties());

    try {
        sessionFactory.afterPropertiesSet();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty(&quot;hibernate.connection.driver_class&quot;));
    dataSource.setUrl(environment.getRequiredProperty(&quot;hibernate.connection.url&quot;));
    dataSource.setUsername(environment.getRequiredProperty(&quot;hibernate.connection.username&quot;));
    dataSource.setPassword(environment.getRequiredProperty(&quot;hibernate.connection.password&quot;));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put(&quot;hibernate.dialect&quot;, environment.getRequiredProperty(&quot;hibernate.dialect&quot;));
    properties.put(&quot;hibernate.show_sql&quot;, environment.getRequiredProperty(&quot;hibernate.show_sql&quot;));
    properties.put(&quot;hibernate.format_sql&quot;, environment.getRequiredProperty(&quot;hibernate.format_sql&quot;));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(s);
    return txManager;
}
}
</code></pre>
<p>GenericDaoImpl is:</p>
<pre><code>@Repository
public abstract class GenericDAOImpl&lt;T&gt; implements DAO&lt;T&gt; {

    @Autowired
    private SessionFactory sessionFactory;

protected Session getSession() {
            return sessionFactory.getCurrentSession();
        }
}
</code></pre>
<p>Every DAO extends this class and has his own @Repository annotation.</p>
<p>Every service is annotated as @transactional. This is the implementation of the UserDetailsService:</p>
<pre><code>@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService, MyUserDetailsService {

    @Autowired private DeveloperService devService;
    @Autowired private AuthorizationService authorizationService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username == null) {
            throw new UsernameNotFoundException(&quot;User not found&quot;);
        }
        Developer dev = devService.findByUsername(username);

        if(dev == null) {
            throw new UsernameNotFoundException(&quot;User not found&quot;);
        }
        MyUserDetails user = new MyUserDetails();
        user.setUsername(dev.getUsername());
        user.setPassword(dev.getPassword());
        user.setMaxAuthorityByIndex(dev.getRole());
        return user;
    }
</code></pre>
<p>I really don't know what this could be. Maybe a wrong configuration on server? To me it appears to be correct...</p>