找不到Spring OpenSessionInViewFilter和sessionFactory bean

时间:2014-05-01 11:51:01

标签: java spring hibernate

我试图在我的Spring MVC应用程序中添加OpenSessionInViewFilter,因为访问Thymeleaf模板中的集合会导致LazyInitializationException。这就是我所拥有的:

public class ApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ApplicationContext.class);
        rootContext.setDisplayName("Test");

        servletContext.addListener(new ContextLoaderListener(rootContext));

        ServletRegistration.Dynamic dispatcher =
                servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        FilterRegistration.Dynamic filter = servletContext.addFilter("openSessionInViewFilter", OpenSessionInViewFilter.class);
        filter.setInitParameter("singleSession", "true");
        filter.addMappingForServletNames(null, true, "dispatcher");

    }

}

@Configuration
@EnableWebMvc
@ComponentScan
@Import({ SecurityConfig.class })
@PropertySource("classpath:application.properties")
@EnableJpaRepositories("test.model")
public class ApplicationContext extends WebMvcConfigurerAdapter {

    @Autowired
    public StringToCompany stringToCompany;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/**");
        registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/**");
        registry.addResourceHandler("/images/**").addResourceLocations("/resources/images/**");
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(stringToCompany);
    }

    @Bean
    public SessionBean sessionBean() {
        return new SessionBean();
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource datasource = new DriverManagerDataSource();
        ...
        return datasource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        LocalContainerEntityManagerFactoryBean factoryBean
                = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource( dataSource() );
        factoryBean.setPackagesToScan( new String[ ] { "test.model" } );
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        factoryBean.setJpaVendorAdapter( vendorAdapter );
        factoryBean.setJpaProperties( this.additionalProperties() );
        return factoryBean;
    }

    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                this.entityManagerFactory().getObject() );
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        ...
        return properties;
    }

}

这导致

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined

我希望它可以像添加这样的样本一样:

@Bean
public AnnotationSessionFactoryBean sessionFactory() {
    return new AnnotationSessionFactoryBean();
}

但这会导致一堆

java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;

我终于尝试将AnnotationSessionFactoryBean更改为LocalSessionFactoryBean(Hibernate 4),但这给了我

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

任何人都可以帮我将OpenSessionInViewFilter集成到我当前的设置中吗?我试图不使用xml。

2 个答案:

答案 0 :(得分:0)

在Spring 4中添加OpenEntityManagerInViewFilter

public class WebContextInitializer implements WebApplicationInitializer{

@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(Application.class);
    rootContext.setServletContext(servletContext);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

    FilterRegistration.Dynamic filter = servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class);
    filter.setInitParameter("singleSession", "true");
    filter.addMappingForServletNames(null, true, "dispatcher");

    /**
     * Add Spring ContextLoaderListener
     */
    servletContext.addListener(new ContextLoaderListener(rootContext));
}}

答案 1 :(得分:0)

或者在Spring.xml中的web.xml中添加OpenEntityManagerInViewFilter:

<filter>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    <init-param>
        <param-name>singleSession</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>