No CurrentSessionContext configured

Your configuration and usage of hibernate is wrong. You are using Spring and even better Spring Boot, however what you posted tries very hard not to use those frameworks and tries to work around them. I strongly suggest using Spring Boot and let that configure the things for you.

First delete your HibernateUtils, burry it deep and never look at it again. You can also delete your AppConfig as Spring Boot can and will take care of the DataSource.

Next create a file called application.properties in your src/main/resources directory and put the following content in there.

spring.datasource.url=jdbc:mysql://localhost/mysql
spring.datasource.username=root
spring.datasource.password=

This will automatically configure a DataSource for you. You don't need the driver as that is deduced from the url you provide. Next add the following properties to configure JPA.

spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

For more settings and properties I suggest a read of the Spring Boot Reference Guide for the properties check this comprehensive list.

Next in your WebApplicationStarter add the HibernateJpaSessionFactoryBean to expose the created JPA EntityManagerFactory as a SessionFactory.

@Configuration
@EnableAutoConfiguration
@ComponentScan("com.mytest")
public class WebApplicationStarter extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplicationStarter.class);
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = SpringApplication.run(WebApplicationStarter.class, args);
    }

    @Bean
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
        return hemf.getSessionFactory();
    }
}

Then just @Autowire the SessionFactory into your UserServiceImpl.

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SessionFactory sessionFactory;

}

Now you can just use the SessionFactory.


I got this error because I had

sessionFactory.getCurrentSession();

when I changed it to

sessionFactory.openSession();

it worked fine.