Hibernate: не удалось лениво инициализировать коллекцию ролей, ни один сеанс или сеанс не был закрыт

Мой код:

    @Test
public void testAddRoleAndAddUser() {

    Role r = roleDao.findByProperty("name", "admin");
    if(r == null) {
        r = new Role();
        r.setName("admin");
        r.setDescription("Just administrator.");
        roleDao.save(r);
    }

    User u = dao.get(1l);
    Set<Role> roles = u.getRoleSet();
    logger.debug("Roles is null: " + (roles == null));
    roles.add(r);
    dao.save(u);
}

13: 39: 41,041 ОШИБКА: org.hibernate.LazyInitializationException не удалось лениво инициализировать Коллекция ролей: xxx.entity.core.User.roleSet, нет сессия или сессия была закрыта org.hibernate.LazyInitializationException: не удалось лениво инициализировать Коллекция ролей: xxx.entity.core.User.roleSet, нет сессия или сессия была закрыта в org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException (AbstractPersistentCollection.java:380) в org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected (AbstractPersistentCollection.java:372) в org.hibernate.collection.AbstractPersistentCollection.initialize (AbstractPersistentCollection.java:365) в org.hibernate.collection.PersistentSet.add (PersistentSet.java:212) в sg.com.junglemedia.test.dao.impl.hibernate.UserDaoTest.testAddRoleAndAddUser (UserDaoTest.java:40) в sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Метод) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) в java.lang.reflect.Method.invoke (Method.java:597) в org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall (FrameworkMethod.java:44) в org.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:15) в org.junit.runners.model.FrameworkMethod.invokeExplosively (FrameworkMethod.java:41) в org.junit.internal.runners.statements.InvokeMethod.evaluate (InvokeMethod.java:20) в org.junit.internal.runners.statements.RunBefores.evaluate (RunBefores.java:28) в org.junit.runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:76) в org.junit.runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:50) в org.junit.runners.ParentRunner $ 3.run (ParentRunner.java:193) в org.junit.runners.ParentRunner $ 1.schedule (ParentRunner.java:52) в org.junit.runners.ParentRunner.runChildren (ParentRunner.java:191) в org.junit.runners.ParentRunner.access $ 000 (ParentRunner.java:42) в org.junit.runners.ParentRunner $ 2.evaluate (ParentRunner.java:184) в org.junit.runners.ParentRunner.run (ParentRunner.java:236) в org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run (JUnit4TestReference.java:46) в org.eclipse.jdt.internal.junit.runner.TestExecution.run (TestExecution.java:38) в org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:467) в org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:683) в org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (RemoteTestRunner.java:390) в org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (RemoteTestRunner.java:197)

Кто-нибудь может помочь?

23
задан Visruth 4 June 2015 в 16:19
поделиться

1 ответ

Скорее всего, вы закрываете сеанс внутри RoleDao. Если вы закроете сеанс, а затем попытаетесь получить доступ к полю объекта, который был загружен лениво, вы получите это исключение. Вероятно, вам следует открыть и закрыть сеанс / транзакцию в своем тесте.

4
ответ дан 29 November 2019 в 01:07
поделиться
Другие вопросы по тегам:

Похожие вопросы: