2013-08-21 2 views
0

Первым я использую Sping 3.1.1 ТранзактнойПружина Транзактный - Hibernate4 Ленивое поле + Hibernate.initialize() = сбор не связан с какими-либо сессиями

<bean id="transactionManagerHLDC01" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="sessionFactoryHLDC01" /> 
    <qualifier value="hldc01"/> 
</bean> 

и спящего режима 4.2.3

<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> 

Также у меня есть Главный entityt (ME) с

@OneToMany(fetch=FetchType.LAZY, mappedBy="host") // <- field in DovecotEmailDomain 
@Fetch(FetchMode.SELECT) 
private Set<DovecotEmailDomain> domains; 

и дочернего объекта (CE)

Когда я вызываю ME.getDomains() Он запускает Hibernate activitites, но он не находится в пределах уже закрытого TRANSACTION.

Возникает вопрос:

Как я могу покрыть Hibernate деятельность с существующей транзакции в HEBERNATE4 + SPRING 3.1?

+0

Вы вызываете ME.getDomains() внутри jsp? Какая ошибка вы получаете? Как вы обрабатываете открытие транзакций? –

+0

Привет Emanuele, 1. Когда я не использую Hibernate.initialize (ME.getDomains()) Я получил сообщение об ошибке: Исключение в потоке «основного» org.hibernate.LazyInitializationException: не удалось инициализировать лениво коллекцию роли: ru.hostlux.emailmanager.entity.hldovecot .DovecotHost.domains, не удалось инициализировать прокси-сервер. no Session – AnNik

+0

2. Когда я использую Hibernate.initialize (...), ошибка: Исключение в теме "main" org. hibernate.HibernateException: коллекция не связана с какой-либо сессией. – AnNik

ответ

0
[02:09:16.147] [DEBUG] r.h.emailmanager.InitDBTestValue - >>> step03() 
[02:09:16.148] [DEBUG] org.hibernate.impl.SessionImpl - opened session at timestamp: 13772093561 
[02:09:16.148] [DEBUG] org.hibernate.jdbc.ConnectionManager - opening JDBC connection 
[02:09:16.169] [DEBUG] o.h.transaction.JDBCTransaction - begin 
[02:09:16.169] [DEBUG] o.h.transaction.JDBCTransaction - current autocommit status: true 
[02:09:16.169] [DEBUG] o.h.transaction.JDBCTransaction - disabling autocommit 
[02:09:16.170] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) 
[02:09:16.170] [DEBUG] org.hibernate.SQL - 
    select 
     this_.id as id2_0_, 
     this_.created as created2_0_, 
     this_.fqdn as fqdn2_0_, 
     this_.hostname as hostname2_0_, 
     this_.isEnable as isEnable2_0_, 
     this_.status as status2_0_, 
     this_.updated as updated2_0_ 
    from 
     dovecothost this_ 
    where 
     this_.hostname=? 
Hibernate: 
    select 
     this_.id as id2_0_, 
     this_.created as created2_0_, 
     this_.fqdn as fqdn2_0_, 
     this_.hostname as hostname2_0_, 
     this_.isEnable as isEnable2_0_, 
     this_.status as status2_0_, 
     this_.updated as updated2_0_ 
    from 
     dovecothost this_ 
    where 
     this_.hostname=? 
[02:09:16.170] [TRACE] o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - abn-host-test-2.com 
[02:09:16.179] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0) 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [2] as column [id2_0_] 
[02:09:16.179] [DEBUG] org.hibernate.loader.Loader - result row: EntityKey[ru.hostlux.emailmanager.entity.hldovecot.DovecotHost#2] 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [2013-08-23 02:09:15.888] as column [created2_0_] 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [abn-host-test-2.com] as column [fqdn2_0_] 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [abn-host-test-2.com] as column [hostname2_0_] 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [true] as column [isEnable2_0_] 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [A] as column [status2_0_] 
[02:09:16.179] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [2013-08-23 02:09:15.888] as column [updated2_0_] 
[02:09:16.179] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1) 
[02:09:16.179] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1) 
[02:09:16.179] [DEBUG] org.hibernate.engine.TwoPhaseLoad - resolving associations for [ru.hostlux.emailmanager.entity.hldovecot.DovecotHost#2] 
[02:09:16.179] [DEBUG] org.hibernate.engine.TwoPhaseLoad - done materializing entity [ru.hostlux.emailmanager.entity.hldovecot.DovecotHost#2] 
[02:09:16.179] [DEBUG] o.h.e.StatefulPersistenceContext - initializing non-lazy collections 
[02:09:16.179] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) 
[02:09:16.179] [DEBUG] org.hibernate.SQL - 
    select 
     this_.id as id2_0_, 
     this_.created as created2_0_, 
     this_.fqdn as fqdn2_0_, 
     this_.hostname as hostname2_0_, 
     this_.isEnable as isEnable2_0_, 
     this_.status as status2_0_, 
     this_.updated as updated2_0_ 
    from 
     dovecothost this_ 
    where 
     this_.hostname=? 
Hibernate: 
    select 
     this_.id as id2_0_, 
     this_.created as created2_0_, 
     this_.fqdn as fqdn2_0_, 
     this_.hostname as hostname2_0_, 
     this_.isEnable as isEnable2_0_, 
     this_.status as status2_0_, 
     this_.updated as updated2_0_ 
    from 
     dovecothost this_ 
    where 
     this_.hostname=? 
[02:09:16.180] [TRACE] o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - abn-host-test-2.com 
[02:09:16.183] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0) 
[02:09:16.183] [TRACE] o.h.t.descriptor.sql.BasicExtractor - found [2] as column [id2_0_] 
[02:09:16.183] [DEBUG] org.hibernate.loader.Loader - result row: EntityKey[ru.hostlux.emailmanager.entity.hldovecot.DovecotHost#2] 
[02:09:16.183] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1) 
[02:09:16.183] [DEBUG] org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1) 
[02:09:16.183] [DEBUG] o.h.e.StatefulPersistenceContext - initializing non-lazy collections 
[02:09:16.183] [DEBUG] o.h.transaction.JDBCTransaction - commit 
[02:09:16.185] [DEBUG] o.h.transaction.JDBCTransaction - re-enabling autocommit 
[02:09:16.185] [DEBUG] o.h.transaction.JDBCTransaction - committed JDBC Connection 
[02:09:16.185] [DEBUG] org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the sessi 
on to release JDBC resources! 
[02:09:16.188] [DEBUG] org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globall 
y: 0)] 
[02:09:16.188] [DEBUG] org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the sessi 
on to release JDBC resources! 
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ru.hostlux.emailmanager.entity.hldovecot 
.DovecotHost.domains, no session or session was closed 
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383) 
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375) 
    at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122) 
    at org.hibernate.collection.PersistentSet.size(PersistentSet.java:162) 
    at ru.hostlux.emailmanager.InitDBTestValue.step03(InitDBTestValue.java:227) 
    at ru.hostlux.emailmanager.InitDBTestValue.main(InitDBTestValue.java:94) 


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.1.xsd 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
     "> 

    <bean id="sessionFactoryHLDC01" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 

     <property name="dataSource"> 
      <ref bean="dataSourceHLDC01" /> 
     </property> 

     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> 
       <!-- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> --> 
       <prop key="hibernate.show_sql">true</prop> 
       <!-- +1 --> 
       <prop key="hibernate.format_sql">true</prop> 
       <prop key="hibernate.hbm2ddl.auto">create</prop> <!-- create | validate --> 

       <prop key="hibernate.current_session_context_class" >org.springframework.orm.hibernate3.SpringSessionContext</prop> 
      </props> 
     </property> 

     <!-- Where located ENTITY: --> 
     <property name="packagesToScan" value="ru.hostlux.emailmanager.entity.hldovecot" /> 

     <!-- HIBERNATE 3 only --> 
     <property name="configurationClass"> 
      <value>org.hibernate.cfg.AnnotationConfiguration</value> 
     </property> 

     <!-- HIBERNATE 3 --> 
     <property name="exposeTransactionAwareSessionFactory"> 
      <value>false</value> 
     </property> 
    </bean> 

    <!-- --> 
    <bean id="transactionManagerHLDC01" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
     p:sessionFactory-ref="sessionFactoryHLDC01"> 
     <qualifier value="hldc01" /> 
    </bean> 

    <tx:annotation-driven transaction-manager="transactionManagerHLDC01" /> 

</beans> 

фрагмент:

public class InitDBTestValue 
{ 
    // Level : TRACE,DEBUG,INFO,WARN,ERROR,OFF 
    private static Logger      LOG     = LoggerFactory 
                     .getLogger(InitDBTestValue.class); 
    private final IDovecotEmailDomainService dovecotEmailDomainService; 
    private final IDovecotHostService   dovecotHostService; 

    public static final String    TEST_HOST_NAME_1  = "ABN-HOST-TEST-1.info"; 
    public static final String    TEST_HOST_NAME_2  = "ABN-HOST-TEST-2.com"; 

    public static final String    TEST_DOMAIN_NAME_1_1 = "abnTestDomain01-01.com"; 
    public static final String    TEST_DOMAIN_NAME_1_2 = "abnTestDomain01-02.com"; 
    private static final String    TEST_DOMAIN_NAME_2_1 = "abnTestDomain02-01.com"; 
    private static final String    TEST_DOMAIN_NAME_2_2 = "abnTestDomain02-02.com"; 

    /** 
    * Constructor. 
    */ 
    public InitDBTestValue() 
    { 

     // src/main/resources/META-INF/spring/applicationContext.xml 
     final GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); 
//  ctx.load("classpath:**/applicationContext.xml"); 
     ctx.load("file:src/main/resources/META-INF/spring/applicationContext.xml"); 
     ctx.refresh(); 

     dovecotHostService = ctx.getBean("dovecotHostService", IDovecotHostService.class); 

     dovecotEmailDomainService = ctx.getBean("dovecotEmailDomainService", 
      IDovecotEmailDomainService.class); 

    } 

    /** 
    * @param args 
    * 
    */ 
    public static void main(final String[] args) 
    { 
     final InitDBTestValue init = new InitDBTestValue(); 

     init.step01(); 
     init.step02Host02Domain01(); 
     // 
     init.step03(); 
    } 

..... 
    /** 
    * Read 
    * 
    */ 
    public void step03() 
    { 
     LOG.debug(" >>> step03() "); 

     final String hostname = InitDBTestValue.TEST_HOST_NAME_2; 
     final String fqdn = InitDBTestValue.TEST_HOST_NAME_2; 
     final Boolean isEnable = true; 
     final Date created = new Date(); 
     final Date updated = new Date(); 

     final DovecotHost host = dovecotHostService.findByHostname(TEST_HOST_NAME_2); 
     if (host != null) 
     { 
//   Hibernate.initialize(host.getDomains()); 

      final Set<DovecotEmailDomain> domains; 

      domains = host.getDomains(); 
      LOG.info(" >> HOST : " + host.getHostname() + "; size of domains=" + domains.size()); 

//   LOG.info(" >> HOST : " + host.getHostname() + "; size of domains=" 
//    + dovecotHostService.getDomainsSize(host)); 

     } 
    } 
} 

Сессия закрыта точно после вызова: dovecotHostService.findByHostname (TEST_HOST_NAME_2); потому, что этот метод является TRANSACTIONAL:

@Override 
@Transactional(value = "hldc01", readOnly = true) 
public DovecotHost findByHostname(final String domainName) { 
    DovecotHost host = null; 
    try { 
     host = dovecotHostDAO.findByProperty(DovecotHost.class, "hostname", domainName.toLowerCase()); 

    } catch (final ABNExceptionMoreOneRecords e) { 
     LOG.error("findByHostname() failed!", e); 
    } 
    return host; 
} 

кстати dovecotHostDAO.findByProperty() также является транзакционной. в любом случае нет никакой сессии, которая применима для инициализации LAZY.

И dovecotHostDAO:

@Repository("dovecotHostDAO") 
@Transactional("hldc01") 
public class DovecotHostDAO extends ABNAbstractHibernateGenercDaoImpl<DovecotHost> implements IDovecotHostDAO 
{ 
    /** 
    * serialVersionUID long DovecotEmailDAO.java 
    */ 
    private static final long serialVersionUID = 1L; 

    // Level : TRACE,DEBUG,INFO,WARN,ERROR,OFF 
    private static Logger  LOG    = LoggerFactory.getLogger(DovecotHostDAO.class); 

    /** 
    * Constructor. Setup SessionFactory. 
    * 
    * @param sessionFactory 
    */ 
    @Autowired 
    public DovecotHostDAO(@Qualifier("sessionFactoryHLDC01") final SessionFactory sessionFactory) 
    { 
     // 
     super(sessionFactory); 
    } 

} 

и там я сессия, как:

public abstract class ABNAbstractHibernateGenercDaoImpl<T> implements IABNHibernateGenericDao<T> 
{ 
    // this field should be define in child. NOT AUTOWIRED! 
    protected SessionFactory sessionFactory; 

    private final Class<T> type; 
.... 

    public ABNAbstractHibernateGenercDaoImpl(final SessionFactory sessionFactory) { 
     // 
     this(); 
     this.sessionFactory = sessionFactory; 
    } 

Может быть есть некоторые свойства или параметры, которые расширяют сессии для таких действий, как отложенная загрузка? Или может быть лучший способ - горячий ленивый init может создать/получить новую/текущую сессию?

 Смежные вопросы

  • Нет связанных вопросов^_^