Spring5开放会话在视图中

j2qf4p5b  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(206)

我试图用Spring5实现opensessioninview模式(反模式)。我在webmvcconfigurer中通过java(而不是xml)配置opensessioninview,并观察它似乎已经在运行的日志。但是当我尝试加载一个懒惰的集合时,它会说已知的“couldnotwritejson:failedly初始化一个role:..."
我在日志里看到了一些疯狂的东西:

DEBUG [http-nio-8080-exec-7] (OpenSessionInViewInterceptor.java:128) - Opening Hibernate Session in OpenSessionInViewInterceptor
DEBUG [http-nio-8080-exec-7] (AbstractPlatformTransactionManager.java:370) - Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
DEBUG [http-nio-8080-exec-7] (JpaTransactionManager.java:393) - Opened new EntityManager [SessionImpl(1867707287<open>)] for JPA transaction
DEBUG [http-nio-8080-exec-7] (DriverManagerDataSource.java:144) - Creating new JDBC DriverManager Connection to [jdbc:mysql://MYIP:3306/DB_NAME?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Europe/Madrid]
DEBUG [http-nio-8080-exec-7] (DataSourceUtils.java:186) - Setting JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2e6ff9ac] read-only
DEBUG [http-nio-8080-exec-7] (TransactionImpl.java:56) - On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
...
...
...
WARN [http-nio-8080-exec-7] (AbstractHandlerExceptionResolver.java:199) - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: com....Route.styles, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role...
DEBUG [http-nio-8080-exec-7] (OpenSessionInViewInterceptor.java:153) - Closing Hibernate Session in OpenSessionInViewInterceptor

因此,会话似乎是按应该的方式打开的,而不是在抛出异常时关闭的。但是我的整个经理没有使用那个会话。。。我说的对吗?我怎样才能做到这一点?
谢谢!
编辑:
我的webconfig.java:

@Configuration
@ComponentScan
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

@Value( "${resources.files.location}" )
private String fileLocation;

@Autowired
DataSource datasource;

@Autowired
private Environment env;

@Bean
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("Messages");
    messageSource.setCacheMillis(10);
    return messageSource;
}

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.getDefault());
    return localeResolver;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
    localeInterceptor.setIgnoreInvalidLocale(true);
    localeInterceptor.setParamName("idioma");
    return localeInterceptor;
}

@Bean
public PlatformTransactionManager hibernateTransactionManager() {
    HibernateTransactionManager transactionManager
            = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactoryBean().getObject());
    return transactionManager;
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();

    internalResourceViewResolver.setPrefix("/WEB-INF/views/");
    internalResourceViewResolver.setSuffix(".jsp");
    return internalResourceViewResolver;
}

public void addInterceptors(InterceptorRegistry registry) {
    OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor();
    openSessionInViewInterceptor.setSessionFactory(sessionFactoryBean().getObject());

    registry.addWebRequestInterceptor(openSessionInViewInterceptor).addPathPatterns("/**");

    registry.addInterceptor(new miLoggerInterceptor());
    registry.addInterceptor(localeChangeInterceptor());
}

@Bean
public FilterRegistrationBean openEntityManagerInViewFilter() {
    FilterRegistrationBean reg = new FilterRegistrationBean();
    reg.setName("OpenEntityManagerInViewFilter");
    reg.setFilter(new OpenEntityManagerInViewFilter());
    return reg;
}

@Bean
public LocalSessionFactoryBean sessionFactoryBean() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(datasource);
    sessionFactory.setPackagesToScan("my.package");
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

private Properties hibernateProperties() {
    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    jpaProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    jpaProperties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
    return jpaProperties;
}

public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/js/**").addResourceLocations("/js/");
    registry.addResourceHandler("/css/**").addResourceLocations("/css/");
    registry.addResourceHandler("/img/**").addResourceLocations("/img/");
    registry.addResourceHandler("/.well-known/acme-challenge/**").addResourceLocations("/.well-known/acme-challenge/");
    registry.addResourceHandler("/webfonts/**").addResourceLocations("/webfonts/");
    registry.addResourceHandler("/multimedia/").addResourceLocations("file:"+fileLocation);

    registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

    registry.addResourceHandler("/files/**").addResourceLocations("file:///C:/tmp/images/");
    registry.addResourceHandler("/favico.ico").addResourceLocations("/favico.ico");
}

}

businessconfig.java文件:

@Configuration
@ComponentScan
@PropertySources({
    @PropertySource("classpath:application.properties"),
})
@EnableJpaRepositories("com.muskers.web.business.repositories")
public class BusinessConfig {

@Autowired
private Environment env;

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("db.driver"));
    dataSource.setUrl(env.getProperty("db.url"));
    dataSource.setUsername(env.getProperty("db.username"));
    dataSource.setPassword(env.getProperty("db.password"));
    return dataSource;
}

@Bean
public PasswordEncoder delegatingPasswordEncoder() {
    PasswordEncoder defaultEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    Map<String, PasswordEncoder> encoders = new HashMap<>();
    encoders.put("bcrypt", new BCryptPasswordEncoder());
    encoders.put("scrypt", new SCryptPasswordEncoder());
    encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());

    DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(
            "bcrypt", encoders);
    passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder);
    return passwordEncoder;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource());
    emf.setPackagesToScan(User.class.getPackage().getName());

    HibernateJpaVendorAdapter hibernateJpa = new HibernateJpaVendorAdapter();
    hibernateJpa.setDatabase(Database.MYSQL);
    hibernateJpa.setDatabasePlatform(env.getProperty("hibernate.dialect"));
    hibernateJpa.setGenerateDdl(env.getProperty("hibernate.generateDdl", Boolean.class));
    hibernateJpa.setShowSql(env.getProperty("hibernate.show_sql", Boolean.class));
    emf.setJpaVendorAdapter(hibernateJpa);

    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    jpaProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    jpaProperties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
    emf.setJpaProperties(jpaProperties);

    return emf;
}

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

@PostConstruct
public void setTimeZone() {
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/Madrid"));
}

public class Roles {
    public final static String ROLE_USER = "USER";
    public final static String ROLE_ADMIN = "ADMIN";
}

public class Authorities {
    public final static String MANAGE_GYMS = "MANAGE_GYMS";
    public final static String MANAGE_USERS = "MANAGE_USERS";
    public final static String READ_GYMS = "READ_GYMS";
    public final static String CREATE_GYMS = "CREATE_GYMS";
    public final static String CREATE_ROUTES = "CREATE_ROUTES";
    public final static String READ_ROUTES = "READ_ROUTES";
    public final static String MANAGE_ROUTES = "MANAGE_ROUTES";
}
}

应用程序.java:

public class App  extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[] { BusinessConfig.class, WebSecurityConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[] { WebConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected Filter[] getServletFilters() {
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    return new Filter[] { characterEncodingFilter};
}

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题