1

我正在尝试将我的 POJO 映射到 DTO。我没有任何自定义字段映射器,因为我的 DTO 中的所有字段都与我的 POJO 中的相同。但是我的 POJO 涉及到多个级别的映射。我的问题是当我试图将 POJO 的内容复制到 DTO 时,我得到了 LazyInitializationException。这是引发异常的代码。

public TestInfoDTO startTest(long testId)
{
    TestInfo info = testDAO.startTest(testId);

    Mapper mapper = new DozerBeanMapper();
    try
    {
        // Exception thrown here.
        infoDTO = mapper.map(info, TestInfoDTO.class);

    } catch(Exception e) {
        LOGGER.info("Exception Thrown While Mapping POJO to DTO");
        e.printStackTrace();
    }
    return infoDTO;
}

这是我的 POJO。

@Entity
@Table(name = "TEST_INFO")
public class TestInfo implements Serializable,IAuditLog
{
private static final long serialVersionUID = 1L;

private long test_ID;
private String test_name;
private Date creation_date;
private String instructions;
private TestPaperInfo testPaperInfo;
private List<TestResults> testResults;
private List<TestResponse> testResponses;
private List<TestUtility> testUtility;

//Getters and setters with hibernate annotations.
}

这是我的 DTO

public class TestInfoDTO 
{
private long test_ID;
private String test_name;
private Date creation_date;
private String instructions;
private TestPaperInfo testPaperInfo;
private List<TestResults> testResults;
private List<TestResponse> testResponses;
private List<TestUtility> testUtility;

//Getters and Setters.
}

在上面的 POJO 中,TestPaperInfo 具有另一个类的 Collection,该类又具有一系列问题,每个问题都有一个 Answers 集合。它们都使用 JPA 注释进行映射。

我已经检查了我从 DAO 获得的“信息”对象的内容,并且一切都存在。但是当我试图将它复制到 DTO(“infoDTO”对象)时,会抛出 LazyInitializationException。这是我第一次使用 DTO 和推土机,所以任何人都可以建议我是否遗漏了什么?或者问题是什么?提前致谢。

4

1 回答 1

1

我猜 testDAO 是@Transactionnal。这意味着一旦 testDAO.startTest 完成,事务就会关闭。

除非交易是事先开始的。在您的主 startTest 函数上放置一个 @Transactionnal 注释。这样,当推土机映射到 DTO 并且可以访问代理模型 TestInfo 时,事务仍然是打开的。

于 2013-09-20T13:42:19.287 回答