我有一个基于Spring的webapp,我的问题是在我的代码发生变化后,我开始变得懒惰加载异常。下面我详细描述一下情况:
一开始
我有一个帐户和Word实体。一个帐户可以有多个单词,一个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;
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;
}
上面的代码没有延迟加载异常。懒惰取得正确的词。
那么
我必须为每个帐户实施单词组,所以我在项目中添加了新的Group实体。现在除了“WordForToday”没有改变之外,Account和Word之间没有直接关系。现在,一个帐户可以拥有多个组,并且只能将一个组分配给一个帐户[具有连接表的单向一对多]。
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;
此外,一个组可以有多个单词,一个单词可以分配给许多组。
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。
答案 0 :(得分:5)
任务调度程序直接在服务实现上执行该方法,而不是通过代理,因此它不会在该范围内启动@Transactional
并启动Hibernate会话。
尝试创建另一个在WordService
中连接的bean并将计划放在那里,以便在WordService
代理上调用该方法。这应该清除它。
答案 1 :(得分:0)
如果Affe解决方案不起作用,我在方法实现中看到的不同之处是:
getUserRandomWordWithDefinition(account.getUsername());
被实体取代:
getUserRandomWordWithDefinition(account);
在您拨打随机字时,您是否可以关闭交易?因为返回单词或发送帐户参数?