No CurrentSessionContext configured

心已入冬 提交于 2019-11-29 10:31:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!