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

pxy2qtax  于 2023-01-26  发布在  其他
关注(0)|答案(1)|浏览(140)

当我尝试通过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...
}

当测试作为自动生成过程的一部分运行时,测试将失败,并显示上述详细消息。堆栈跟踪确定在访问SecondDomainClass对象的主键时发生错误。
版本:Java 1.7/JUnit 4.10/JPA 2/Spring 3.2.2/Hibernate 4.1.7
提前感谢您的帮助。

sq1bmfud

sq1bmfud1#

  • “无法初始化代理[...] -无会话”* 错误

在服务方法上使用以下注解:

@Transactional(readOnly = true)

相关问题