簡體   English   中英

連續服務器請求導致休眠異常不安全地使用會話的問題

[英]Continuous server request causing issue of hibernate exception unsafe use of session

我已經使用Spring 4.3,Hibernate 5和MySQL 5.6創建了Web應用程序。

從Spring我正在使用-1.Spring處理程序攔截器-過濾每個請求。

2.Spring MVC-管理REST Web資源。

3.Spring AOP-作為事務管理者,采用聲明式方法(@Transactional)

4.Hibernate-ORM和會話連接管理。

應用程序已成功部署在服務器上,並且我能夠登錄。

因此,現在讓我談談我的問題:-我從休眠DAO層引發了一段時間異常后,登錄到應用程序並連續命中該請求(使用f5)。

每次遇到不同的異常,如:-

  1. org.springframework.orm.hibernate5.HibernateSystemException:HHH000479:集合[dao.domain.WebService.webServicePermissionMaps]未被flush()處理。 這可能是由於會話的不安全使用(例如,在多個線程中同時使用,在實體生命周期掛鈎期間進行更新)。

  2. 服務器內部錯誤找到相同集合的兩個表示形式:dao.domain.WebService.webServicePermissionMaps;

3。$ {PATTERN} $ {PATTERN} java.lang.NullPointerException:在org.hibernate.event.internal.AbstractFlushingEventListener.prepareCollectionFlushes(AbstractFlushingEventListener.java:178)處為null〜[hibernate-core-5.2.7.Final.jar: 5.2.7。最終]

4。$ {PATTERN} $ {PATTERN} org.springframework.orm.hibernate5.HibernateSystemException:找到對集合的共享引用:dao.domain.WebService.webServicePermissionMaps; 嵌套的異常是org.hibernate.HibernateException:找到對集合的共享引用:dao.domain.WebService.webServicePermissionMaps。

5.由:java.sql.SQLException:語句關閉后不允許執行任何操作。 在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)〜[mysql-connector-java-5.1.36.jar:5.1.36]

以下是我的代碼:

彈簧配置

@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();
    }
}

數據庫配置類

@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;
}

}

彈簧攔截器

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(希望此類bean進入請求范圍。此類沒有@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("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公共類WebServiceDAOImpl擴展了BaseDAOImpl,實現了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;
    }

} 

問題已解決。 當我在類級別創建會話對象時,這很糟糕。 並且會話對象在線程之間共享。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM