简体   繁体   中英

Loading lazy collection in @Transactional method

I try to load collection to my object (I cannot use FetchType.EAGER), but I am getting following exception:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: Produkt.opinie, could not initialize proxy - no Session

I don't know why as I am doing it in @Transactional scope:

@Service
@Transactional
public class ProduktService extends AbstractService implements IProduktService {


    public Produkt findProduktById(Integer id) {
        Produkt produkt = (Produkt) getSessionFactory().getCurrentSession()
                .get(Produkt.class, id);
            produkt.getOpinie();
        return produkt;
    }
}

There could be many reason. For once having @Transactional annotation is not all it takes -- you need to check a transaction manager has been properly configured in your spring application context. Then you need to check your application has proper AOP support such that Spring can automatically start and finish transaction on methods annotated with @Transactional.

You also need a proper transaction manager, eg: in you case since you're using Hibernate, you need a HibernateTransactionManager configured.

It is also helpful to debug the actual SQL statement issued by Spring / Hibernate to check if you're transaction really works properly

Chapter 11 of the spring manual is a good reading for this topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM