org.hibernate.HibernateException: коллекция не связана ни с одним сеансом - PullRequest
6 голосов
/ 05 января 2012

У моего друга возникла особая проблема в программном обеспечении с открытым исходным кодом OscarMcmaster.Он попросил меня помочь, и я смог добраться до кода, вызывающего проблему.Ниже приведен метод:

 public BillingService getBillingCodeByCode(String code){
    List list = billingServiceDao.findBillingCodesByCode( code,"BC");
    if(list == null || list.size() ==0 ){
        return null;
    }
    return (BillingService) list.get(0);
  }

billingServiceDao инициализируется контейнером Spring:

private static BillingServiceDao billingServiceDao = 
                  (BillingServiceDao) SpringUtils.getBean("billingServiceDao");

В BillingServiceDao классе выполняется следующий код:

public List<BillingService> findBillingCodesByCode(String code, String region) {
    Query query = entityManager.createQuery("select bs  from....");
    query.setParameter("code", code + "%");
    query.setParameter("region", region);

    @SuppressWarnings("unchecked")
    List<BillingService> list = query.getResultList();
    return list;
}

Виновником является query.getResultList();, но я из другой вселенной (.Net) и не знаю, как решить проблему.

Пожалуйста, помогите мне помочь моему другу решить эту проблему.

РЕДАКТИРОВАТЬ: - Трассировка стека

SEVERE: Servlet.service() for servlet action threw exception
org.hibernate.HibernateException: collection is not associated with any session
    at org.hibernate.collection.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:449)
    at org.hibernate.engine.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:797)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:241)
    at org.hibernate.loader.Loader.doList(Loader.java:2220)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
    at org.hibernate.loader.Loader.list(Loader.java:2099)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:66)
    at org.oscarehr.common.dao.BillingServiceDao.findBillingCodesByCode(BillingServiceDao.java:47)
    at org.oscarehr.common.dao.BillingServiceDao$$FastClassByCGLIB$$f613fb7e.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)

Ответы [ 2 ]

4 голосов
/ 05 января 2012

По умолчанию Hibernate заполняет список объектов «лениво», и для этого вам нужен открытый сеанс.Spring открывает и закрывает сеанс Hibernate вокруг вызова DAO.Поэтому, когда вы просматриваете список, Hibernate пытается заполнить его для вас, но обнаруживает, что сеанс закрыт, и выдает ошибку.

Вам необходимо добавить OpenSessionInViewFilter в файл web.xml (при условии, что выпишите веб-приложение), добавьте OpenSessionInViewInterceptor в контекст Spring или просто извлеките содержимое списка перед его возвратом:

return new ArrayList<BillingService>(list);

Также в качестве отступа это:

private static BillingServiceDao billingServiceDao = 
              (BillingServiceDao) SpringUtils.getBean("billingServiceDao");

Во-первых, полностью игнорирует цель использования Spring.

0 голосов
/ 05 декабря 2014

Я видел эту проблему, потому что мне не удалось аннотировать метод в службе с @Transactional.Похоже, что Hibernate закрывает сеанс, когда выполняется вызов другого метода (даже внутри того же класса), если вызывающий не аннотирован соответствующим образом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...