Reputation: 920
I know this has been asked many times (already cheched most of the post here and in other sites), but I dont get to solve my problem.
My setup is: jpa 2 + hibernate 4 + spring 4 + primefaces + jboss eap 7
The problem: I got a lazy collection into another bean, but when I get to call the .size() method on the bean, it throws the "LazyInitializationException: failed to lazily initialize a collection of role: com.pe.controlLines.data.model.Activity.activityRisks, could not initialize proxy - no Session"
Im sure i got an active transaction following this LazyInitializationException Within a @Transactional Method and http://blog.timmattison.com/archives/2012/04/19/tips-for-debugging-springs-transactional-annotation/ so I'm 100% sure theres a transaction running at the time.
My entity clases:
@Entity
public class Company {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long companyId;
@Column
private String name;
@OneToOne(cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
private Activity companieActivities;
@OneToMany
private Collection<SourceSupervision> sourceSupervisions;
and the nested class
@Entity
@Indexed
public class Activity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long activityId;
@ManyToOne
@JoinColumn(name="parentActivityId")
private Activity parent;
@Column
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
@Analyzer(definition = "searchtokenanalyzer")
private String name;
@Column
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
@Analyzer(definition = "searchtokenanalyzer")
private String description;
@OneToMany(cascade={CascadeType.PERSIST, CascadeType.REFRESH})
private Collection<ActivityRisk> activityRisks = new ArrayList<ActivityRisk>();
@ManyToMany(cascade={CascadeType.PERSIST, CascadeType.REFRESH})
private Collection<Word> words;
@ManyToMany
private Collection<Rol> rolesForActivity;
the bussines delegate is anotated like this (the bussines is called from the page controller):
@Component
@Scope("session")
@Transactional
public class SystemConfigurationBussinesDelegate {
Got an inicialization of the reference to the entity, which executes fine. (this is from the aboce class)
private Company currentCompany;
private Risk currentRisk;
@PostConstruct
public void init(){
//((WordDAO)wordDAO).startIndexer();
currentCompany = genericDAO.get(Company.class, 1l);
}
But in this method
public List<Danger> getDangers(){
List<Danger> returnValue = new ArrayList<Danger>();
System.out.println(TransactionSynchronizationManager.isActualTransactionActive());
Hibernate.initialize(currentCompany.getCompanieActivities());
currentCompany.getCompanieActivities().getActivityRisks().size();
for( ActivityRisk aRisk : currentCompany.getCompanieActivities().getActivityRisks() ){
Risk risk = aRisk.getRisk();
if(risk == currentRisk){
returnValue = new ArrayList<Danger>(aRisk.getDangers());
}
}
return returnValue;
}
the sysout returns true so the transaction is active, and I can see an open connection to the database, the Hibernate.inicialize works fine, and the call to currentCompany.getCompanieActivities().getActivityRisks().size(); throws the exception.
Could it be some problem with contexts or somethng similar?
My spring configuration:
<?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:security="http://www.springframework.org/schema/security"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd">
<context:component-scan base-package="com.pe.controlLines" />
<context:annotation-config />
<context:spring-configured />
<aop:aspectj-autoproxy proxy-target-class="true"/>
<jee:jndi-lookup id="myDataSource" jndi-name="java:/ControllinesDS"/>
<!-- Data Source Declaration -->
<!-- Session Factory Declaration <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> -->
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<!-- <property name="packagesToScan">
<list>
<value>net.javabeat.spring.model</value>
</list>
</property>
<property name="annotatedClasses">
<list>
<value>co.com.testTalos.model.Storage</value>
<value>co.com.testTalos.model.Buyer</value>
<value>co.com.testTalos.model.Preferences</value>
</list>
</property>-->
<property name="packagesToScan">
<list>
<value>com.pe.controlLines.data.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
<prop key="hibernate.search.default.indexBase">C:/DEVELOPMENT/lucene/indexes</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
</beans>
Upvotes: 1
Views: 1916
Reputation: 41143
I think your problem is to do with calling the transactional method inside @PostConstruct
. By design spring tx aspects are/may not active on postconstruct method because not all beans guaranteed to have finished constructing. Try searching this topic, I remember encountering this by surprise too but there are plenty helpful articles.
Since then my prefered alternatives when I need tx on postconstruct is to use programmatic transaction (see Spring TransactionTemplate patterns) use the ContextRefreshedEvent. See below example:
@Service
public class MyService implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
// This method will be executed at context startup or refresh
// It is guaranteed all beans have finish constructing, hence
// AOP tx is available
}
...
}
Upvotes: 5