“无法初始化代理 - 没有会话”

时间:2013-07-18 04:48:51

标签: java spring hibernate jpa junit

尝试通过Spring,JPA和Java运行JUnit测试时收到以下错误消息:

“无法初始化代理 - 无会话”

测试是针对域类的(让我们称之为FirstDomainClass)。 FirstDomainClass类有许多字段,包括以多对一关系链接到另一个域类的字段:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "SECOND_DOMAIN_CLASS")
private SecondDomainClass secondDomainClass;

我发现我必须使用FetchType.EAGER,否则当我检索FirstDomainClass的实例时,不会填充SecondDomainClass对象。

FirstDomainClass的DAO实现类的每个方法都以@Transactional注释为前缀:

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void store(FirstDomainClass firstDomainClass) {
    entityManager.persist(firstDomainClass);
}

然后我使用Spring将所有内容连接起来,包括我的DAO实现的bean定义,然后@Autowired到我的JUnit类中。测试类通过@Before方法在数据库中创建一些数据,然后使用@After方法将其清除。

该类以

为前缀
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback = false)
@ContextConfiguration(locations = { ... list of config files... })

......测试看起来像这样:

@Test
public void testStore() {
    SecondDomainClass second = secondDomainClassDao.get(... object created in @Before method... );

    FirstDomainClass first = new FirstDomainClass();
    first.setSecondDomainClass(second);
    ... other setting...
    firstDomainClassDao.store(first);

    FirstDomainClass newFirst = firstDomainClassDao.get(... criteria to retrieve object created by store()... );

    ... assertions here...
}

当测试作为自动构建过程的一部分运行时,它会失败并显示上面详述的消息。 stacktrace标识在访问SecondDomainClass对象的主键时发生错误。

版本:Java 1.7 / JUnit 4.10 / JPA 2 / Spring 3.2.2 / Hibernate 4.1.7

非常感谢您的任何帮助。

0 个答案:

没有答案