Dozer throwing lazyInitializationException

心不动则不痛 提交于 2019-12-23 04:36:12

问题


I'm trying to map my POJO to a DTO. I do not have any custom field mappers as all my fields in my DTO are same as in my POJO. But my POJO has multiple level of mapping involved. My problem is when i'm trying to copy the contents of my POJO to the DTO, i'm getting LazyInitializationException. Here is the code where the exception is thrown.

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;
}

Here is my 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.
}

And this my 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.
}

In the above POJO, the TestPaperInfo has a Collection of another class which in-turn has a collection of questions and each question has a collection of Answers. They are all mapped using JPA annotations.

I have checked the contents of the "info" object that i'm getting from the DAO and everything is present. But when I'm trying to copy it to the DTO ("infoDTO" object) LazyInitializationException is thrown. This is the first time I'm using a DTO and Dozer so could anyone suggest if I'm missing something? Or what the problem is? Thanks in advance.


回答1:


I guess testDAO is @Transactionnal. This means once testDAO.startTest has finished, the transaction is closed.

That is unless the transaction is started before hand. Place a @Transactionnal annotation on your main startTest function. This way the transaction will still be open when dozer maps to a DTO and accessing proxy model TestInfo will be possible.



来源:https://stackoverflow.com/questions/18737476/dozer-throwing-lazyinitializationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!