Tobia
Tobia

Reputation: 9520

Hibernate and spring session configuration

i have a problem with Hiberante and Spring.

When i get an entity everything works, but if I use a subproperty the lazy load fails due to a close session... why hibernate close session so early? Can not wait to exit the service or take one session per thread?

This is my configuration

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.cinebot.db.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

This is my dao:

@Transactional
public class Dao {


    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public <T> T get(Class<T> classe, Serializable id) throws Exception {
        if(id==null) return null;
        T obj = (T) getSession().get(classe, id);
        return obj;
    }

}

and this is where i get the error (getEventi() is lazy loaded) inside a @Service class:

    Spettacoli spettacolo = dao.get(Spettacoli.class, spettacoloId);
   if(spettacolo.getEventi().getScadenza()>0) throw new LogicalException("Spettacolo scaduto");

Upvotes: 0

Views: 696

Answers (1)

Sunil Chavan
Sunil Chavan

Reputation: 3004

You are accessing the entity outside the transaction.. You need to mark service method as transactional.

In your current code your transaction ends when your dao method completes so when you access that entity in your service method it is detached entity which will certainly thorw exception.

Remember you need to start transaction in service and not DAO which will allow you to access child entities. So move @transactional annotation to your service method.

Upvotes: 1

Related Questions