I have an issue with getting session on anonymus inner class in hibernate with spring session factory.
Here is the code:
public class DomainDaoImpl extends BasicDaoImpl<Domain> implements Iterable<Collection<Domain>> {
...
@Override
public Iterator<Collection<Domain>> iterator() {
return (new Iterator<Collection<Domain>>() {
private int counter = 0;
public static final int LIMIT = 100;
...
@Override
@Transactional(readOnly = true)
public Collection<Domain> next() {
final Criteria criteria = getCurrentSession().createCriteria(Domain.class);
final LinkedHashSet<Domain> result = new LinkedHashSet<Domain>();
List resultList = null;
while (!(resultList = criteria.list()).isEmpty()) {
criteria.setFirstResult((counter++ * LIMIT) + 1);
criteria.setMaxResults(LIMIT);
result.addAll(resultList);
}
return result;
}
...
});
The issue is org.hibernate.HibernateException: No Session found for current thread
this happens usually when DAO method is not within transaction.
So how to make it work with an inner class?
i think defining
@Transactional(readOnly = true)at inner class level, spring will not be able to detect and apply transaction aspect over it. so it will not work for sure.but i think if you write something like below might work not 100% sure (i doubt once you invoke iterator method transaction is closed)
another option can be let caller be responsible for transaction or write wrapper method over
iterator()likegetAllDomain()and apply transaction to that method.Solution which worked (mentioned in comments)