Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8920223
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T06:12:53+00:00 2026-06-15T06:12:53+00:00

I have a Spring-based webapp and my problem is after a change in my

  • 0

I have a Spring-based webapp and my problem is after a change in my code I started to get lazy loading exception. Below I describe the situation in details:

In the beginning

I had an Account and Word entities. One account can have many words and one Word can be assigned to many Accounts.

Account.class

@ManyToMany(targetEntity = Word.class, fetch = FetchType.LAZY)
@JoinTable(name = "account_word", joinColumns = {@JoinColumn(name="account_id")}, inverseJoinColumns = {@JoinColumn(name="word_id")})
@OrderBy("word")
private List<Word> words;

Word.class

@ManyToMany(targetEntity = Account.class, fetch = FetchType.LAZY, mappedBy = "words")
@JsonIgnore
private List<Account> accounts;

Except that every Account can have only one “WordForToday” which was represented by Word entity mapped in Account.class like this:

@OneToOne
@JoinColumn(name="word_for_today")
private Word wordForToday;

Everything was working properly. In particular I had a @Scheduled method which was invoked once a day to change the “WordForToday” for every Account:

WordServiceImpl.class

@Transactional
@Service
public class WordServiceImpl implements WordService {

@Autowired
AccountDao accountDao;

@PersistenceContext
EntityManager entityManager;

@Override
@Scheduled(cron="0 0 0 * * ?")
public void setNewWordsForToday() {
    logger.info("Starting setting new Words For Today");
    List<Account> allAccounts = accountDao.listAccounts();
    for(Account account : allAccounts) {    
        if(hasListAtLeastOneWordWithDefinitionWhichIsNotSetAsWordForToday(account.getWords(), account.getUsername())) {
            account.setWordForToday(getUserRandomWordWithDefinition(account.getUsername()));
            entityManager.persist(account);
        }
    }
    logger.info("Setting new Words For Today ended");
}

@Override
@Transactional
public List<Word> listUserWords(String username) {
    try {
        Account foundAccount = accountDao.findUserByUsername(username);
        List<Word> userWords = foundAccount.getWords();
        userWords.size();
        return userWords;
    } catch (UserNotFoundException unf) {
        logger.error("User not found: " + username, unf.getMessage());
        return Collections.emptyList();
    }
}
}

AccountDaoImpl.class

@Override
public Account findUserByUsername(String username) throws UserNotFoundException {
    CriteriaQuery<Account> c = cb.createQuery(Account.class);
    Root<Account> r = c.from(Account.class);
    try {
        c.select(r).where(cb.equal(r.get("username"), username));
        Account foundAccount = entityManager.createQuery(c).getSingleResult();
        return foundAccount;
    } catch(NoResultException nre){
        throw new UserNotFoundException();
    }
}

@Override
public List<Account> listAccounts() {
    CriteriaQuery<Account> cq = cb.createQuery(Account.class);
    Root<Account> account = cq.from(Account.class);
    cq.select(account);
    TypedQuery<Account> q = entityManager.createQuery(cq);
    List<Account> accounts = q.getResultList();
    return accounts;
}

And this code above was without lazy loading exception. Words where lazy fetched properly.


So then

I had to implement Groups of Words for every Account, so I added new Group entity in my project. Now there is no direct relationship between Account and Word except “WordForToday” which didn’t changed. Now one Account can have many Groups and only one Group can be assigned to one Account [unidirectional one-to-many with join table].

Account.class

@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "account_wordgroup", joinColumns = {@JoinColumn(name="account_id")}, inverseJoinColumns = {@JoinColumn(name="wordgroup_id")})
@OrderBy("name")
private List<Group> groups;

Additionally one Group can have many words and one Word can be assigned to many groups.

Group.class

@ManyToMany(targetEntity = Word.class, fetch = FetchType.EAGER)
@OrderBy(value="word")
@JoinTable(name = "wordgroup_word", joinColumns = {@JoinColumn(name="wordgroup_id")}, inverseJoinColumns = {@JoinColumn(name="word_id")})
private List<Word> words;

Word.class

@ManyToMany(targetEntity = Group.class, fetch = FetchType.LAZY, mappedBy = "words")
@JsonIgnore
private List<Group> groups;

And every CRUD methods which use this Entities above are working properly. I only have problem with setNewWordsForToday() method mentioned above which now looks like this (I refactored code a bit):

WordServiceImpl.class

@Transactional
@Service
public class WordServiceImpl implements WordService {

@Autowired
AccountDao accountDao;

@PersistenceContext
EntityManager entityManager;

@Autowired
GroupService groupService;

@Override
@Scheduled(cron="0 0 0 * * ?")
@Transactional
public void setNewWordsForToday() {
    logger.info("Starting setting new Words For Today");
    List<Account> allAccounts = accountDao.listAccounts();
    for(Account account : allAccounts) {    
        if(hasListAtLeastOneWordWithDefinitionWhichIsNotSetAsWordForToday(listUserWords(account), account)) {
            account.setWordForToday(getUserRandomWordWithDefinition(account));
            entityManager.persist(account);
        }
    }
    logger.info("Setting new Words For Today ended");
}

@Override
@Transactional
public List<Word> listUserWords(Account account) {
    List<Group> userGroups = groupService.listUserGroups(account);
    List<Word> userWords = new ArrayList<Word>();
    for(Group userGroup : userGroups) {
        userWords.addAll(userGroup.getWords());
    }
    return userWords;
}
}

GroupServiceImpl.class

@Transactional
@Service
public class GroupServiceImpl implements GroupService {

@Override
@Transactional
public List<Group> listUserGroups(Account account) {
    List<Group> userGroups = account.getGroups();
    userGroups.size();
    return userGroups;
}

}

AccountDaoImpl.class didn’t change. And Now i have this lazy loading exception when @Scheduled method is invoked:

 ERROR [org.springframework.scheduling.support.MethodInvokingRunnable] - Invocation of method 'setNewWordsForToday' on target class [class pl.net.grodek.snd.service.WordServiceImpl] failed
 org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: pl.net.grodek.snd.model.Account.groups, no session or session was closed
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:394)
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:386)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:126)
at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:242)
at pl.net.grodek.snd.service.GroupServiceImpl.listUserGroups(GroupServiceImpl.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy48.listUserGroups(Unknown Source)
at pl.net.grodek.snd.service.WordServiceImpl.listUserWords(WordServiceImpl.java:83)
at pl.net.grodek.snd.service.WordServiceImpl.setNewWordsForToday(WordServiceImpl.java:333)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.support.MethodInvokingRunnable.run(MethodInvokingRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:51)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

I think that i tried everything and I have no more idea what to do. It is blocking me for a couple of days for now so please anyone help me with this 🙁

PS: I am using OpenEntityManagerInViewFilter of course.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T06:12:54+00:00Added an answer on June 15, 2026 at 6:12 am

    The task scheduler is executing that method directly on the service implementation, not going through the Proxy, so it is not picking up the @Transactional and starting a Hibernate Session at that scope.

    Try creating another bean that wires in WordService and put the schedule there, so that you invoke the method on the WordService proxy. That should clear it up.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a spring based webapp that persists data with Hibernate. The default web
I'm developing a simple webapp based on Spring framework. I have these two files
I have a spring based webapp and I also have a background process. From
I have a Spring based WebApp. In my application context, I have this bean
I have a Spring-MVC based webapp with a JSP front end. It is your
I have a webapp based on Spring 3.0.6 which works fine on Tomcat 7.0.
Here we have a Spring based webapp in google apps engine. I've created a
I have a spring-based Web Service. I now want to build a sort of
I have a localized spring mvc based web application, that has an externalized messages
We have a Spring + Ibatis based J2EE app. I planned to wrap around

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.