简体   繁体   中英

Continuous server request causing issue of hibernate exception unsafe use of session

I have created Web application using - Spring 4.3, hibernate 5 and MySQL 5.6.

From Spring i am using - 1.Spring handler interceptor - for filtering each request.

2.Spring MVC - To manage the REST web resource.

3.Spring AOP - As Transaction manager with declarative approach(@Transactional)

4.Hibernate - ORM and session connection management.

Application is deployed successfully on server and i am able to login.

So now lets talk about my problem :- i logged into application and continuously hitting the request(using f5) after some time exception is thrown from hibernate DAO layer.

every time getting different exceptions like :-

  1. org.springframework.orm.hibernate5.HibernateSystemException: HHH000479: Collection [dao.domain.WebService.webServicePermissionMaps] was not processed by flush(). This is likely due to unsafe use of the session (eg used in multiple threads concurrently, updates during entity lifecycle hooks).;

  2. Internal server error Found two representations of same collection: dao.domain.WebService.webServicePermissionMaps;

3.${PATTERN}${PATTERN} java.lang.NullPointerException: null at org.hibernate.event.internal.AbstractFlushingEventListener.prepareCollectionFlushes(AbstractFlushingEventListener.java:178) ~[hibernate-core-5.2.7.Final.jar:5.2.7.Final]

4.${PATTERN}${PATTERN} org.springframework.orm.hibernate5.HibernateSystemException: Found shared references to a collection: dao.domain.WebService.webServicePermissionMaps; nested exception is org.hibernate.HibernateException: Found shared references to a collection: dao.domain.WebService.webServicePermissionMaps.

5.Caused by: java.sql.SQLException: No operations allowed after statement closed. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998) ~[mysql-connector-java-5.1.36.jar:5.1.36]

Following is my code:-

Spring configuration-

@Configuration
@EnableWebMvc
@Import({DbConfiguration.class})
@ComponentScan(basePackages = "com")
@PropertySource("classpath:application.properties")
public class RestConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor()).excludePathPatterns("/security/authenticate").excludePathPatterns("/security/ssoAuthenticate");
        registry.addInterceptor(authorizationInterceptor()).excludePathPatterns("/security/authenticate").excludePathPatterns("/security/ssoAuthenticate");
    }

    @Bean
    public AuthorizationInterceptor authorizationInterceptor() {
        return new AuthorizationInterceptor();
    }
}

DB config class-

@Configuration

    @EnableTransactionManagement

    public class DbConfiguration {

    @Bean
    public DataSource dataSource() throws NamingException { 
            return (DataSource) new JndiTemplate().lookup(env.getRequiredProperty("jdbc.url"));
        }

@Bean
@Autowired
public LocalSessionFactoryBean sessionFactory() throws NamingException {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[]{"com.dao"});
    sessionFactory.setHibernateProperties(hibProperties());
    return sessionFactory;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sessionFactory);
    return tm;
}

private Properties hibProperties() {
    Properties properties = new Properties();
    properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
    properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, "false");
    return properties;
}

}

Spring Interceptor-

public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

private static Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);

@Autowired
private ApplicationContext appContext;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    //variables declaration
    try {
        servicePath = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

        WebServiceUtil webServiceUtil = (WebServiceUtil)appContext.getBean("webServiceUtil");

        //This method causing hibernate erroe
        boolean isAccessible = webServiceUtil.isWebServiceAccessbile(roles, servicePath, request.getMethod());

    }catch (Exception e) {
        log.error("Error occured in AuthorizationInterceptor.preHandle method role  are : "+roles, e);
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.getWriter().write(e.getMessage());
        return false;
    }
    return true;
}

}

-Util Class(Want this class bean into request scope.This class dont have @Transactional)

@Service("webServiceUtil")
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "request")
public class WebServiceUtil {

@Autowired
private AuthorizationService authorizationService;

public boolean isWebServiceAccessbile(Set<String> roles, String basePath, String methodType)
            throws SysException {

        try {
            List<WebService> webservices = authorizationService.getWebService(roles, methodType);

            List<String> webserviceUrl = new ArrayList<String>();
            for (WebService webService : webservices) {
                webserviceUrl.add(webService.getUrl());
            }

            return webserviceUrl.contains(basePath);
        } catch (SysException e) {
            throw e;
        }
    }
}

-Service Class

@Service("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService {

@Autowired
private WebServiceDAO webServiceDAO;

@Override
    @Transactional
    public List<WebService> getWebService(Set<String> roles, String method) throws DataAccessException {
            return webServiceDAO.getWebServices(roles, method);
    }

}

@Repository public class WebServiceDAOImpl extends BaseDAOImpl implements WebServiceDAO {

private static Logger log = LoggerFactory.getLogger(WebServiceDAOImpl.class);

@Override
public List<WebService> getWebServices(Set<String> roles, String methodType) throws DataAccessException {

    TypedQuery<WebService> query = null;
    try {
        Session session = getSessionFromSessionFactory(getSessionFactory());

        StringBuilder sqlString = new StringBuilder("select ws.* from WEB_SERVICE_PERMISSION_MAP wpm "+ 
                 "join WEB_SERVICE ws on ws.ID = wpm.WEB_SERVICE_ID "+
                 "join WEB_SERVICE_METHOD wsm on wsm.ID = wpm.WEB_SERVICE_METHOD_ID "+
                 "where wpm.PERMISSION_ID in "+
                 "(select pe.id from ROLE_PERMISSION rope "+
                 "inner join Permission pe on rope.PERMISSIONID = pe.id "+
                 "inner join Role ro on rope.ROLEID = ro.ID "+
                 "where ro.name in (:roles)) and "+
                 "wsm.NAME in (:method)");

        query = session.createNativeQuery(sqlString.toString(), WebService.class);
        query.setParameter("roles", roles);
        query.setParameter("method", methodType);

    } catch (Exception e) {
        log.error("Error occured in WebServiceDAOImpl.getWebServices method while getting web services for roles : "+roles+" and request method type : "+methodType, e);
        throw new DataAccessException("Error occured in WebServiceDAOImpl.getWebServices method while getting web services for roles : "+roles+" and request method type : "+methodType, e);
    }
    return query.getResultList();
}

}

-Base DAO

public class BaseDAOImpl<T> implements BaseDAO<T> {

    @Autowired
    private SessionFactory sessionFactory;
    private Session session;
    private Class<T> domainClass;

    public Session getSessionFromSessionFactory(SessionFactory sessionFactory) {
        try {
            session = sessionFactory.getCurrentSession();
        } catch (HibernateException he) {
            log.error("Error in getSessionFromSessionFactory :" + he.getStackTrace());
        }
        return session;

    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

} 

Problem is resolved. It was my bad as i created session object at class level. and session object is shared between threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM