2

我有一个基于 Spring 的 webapp,我的问题是在我的代码更改后,我开始出现延迟加载异常。下面我详细描述一下情况:

在一开始的时候

我有一个 Account 和 Word 实体。一个帐户可以有多个单词,一个单词可以分配给多个帐户。

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;

词类

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

除了每个帐户只能有一个“WordForToday”,它由在 Account.class 中映射的 Word 实体表示,如下所示:

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

一切正常。特别是我有一个@Scheduled 方法,它每天调用一次来更改每个帐户的“WordForToday”:

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;
}

上面这段代码没有延迟加载异常。懒惰正确提取的单词。


那么那么

我必须为每个帐户实现单词组,所以我在我的项目中添加了新的组实体。现在除了没有改变的“WordForToday”之外,Account 和 Word 之间没有直接关系。现在一个Account可以有多个Groups,并且一个Account只能分配一个Group[单向一对多与连接表]。

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;

此外,一个组可以有多个单词,一个单词可以分配给多个组。

组类

@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;

词类

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

并且上面使用此实体的每个 CRUD 方法都可以正常工作。我只有上面提到的setNewWordsForToday()方法有问题,现在看起来像这样(我重构了一点代码):

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 没有改变。现在,当调用 @Scheduled 方法时,我有这个延迟加载异常:

 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)

我想我什么都试过了,我不知道该怎么做。它现在阻止了我几天,所以请任何人帮助我:(

PS:我当然在使用 OpenEntityManagerInViewFilter。

4

2 回答 2

5

任务调度程序直接在服务实现上执行该方法,而不是通过代理,因此它不会在该范围内拾取@Transactional并启动 Hibernate Session。

尝试创建另一个连接到其中的 beanWordService并将调度放在那里,以便您在WordService代理上调用该方法。那应该清除它。

于 2012-11-27T20:22:27.833 回答
0

如果 Affe 解决方案不起作用,我在您的方法实现中看到的不同之处是:

getUserRandomWordWithDefinition(account.getUsername());

替换为实体:

getUserRandomWordWithDefinition(account);

在您调用随机词时,您是否有可能关闭您的交易?因为返回字或发送帐户参数?

于 2012-11-27T20:30:03.753 回答