gpt4 book ai didi

java - 奇怪的延迟加载异常

转载 作者:行者123 更新时间:2023-11-30 06:27:09 24 4
gpt4 key购买 nike

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

一开始

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

账户类

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

除了每个帐户只能有一个“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;
}

并且上面这段代码没有延迟加载异常。 lazy 正确获取的词。


那么

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

账户类

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

并且使用上述实体的每个 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。

最佳答案

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

尝试创建另一个连接 WordService 的 bean 并将计划放在那里,以便您调用 WordService 代理上的方法。这应该清除它。

关于java - 奇怪的延迟加载异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13592223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com