2016-03-05 100 views
0

使用dropwizard 0.9.2和dropwizard-hibernate 0.9.2,我试图检索由@OneToMany与hibernate映射的集合。不幸的是我得到这个异常:Dropwizard未能懒洋洋地初始化一个角色集合

com.fasterxml.jackson.databind.JsonMappingException: failed to lazily 
initialize a collection of role: com.ng.Computer.parts, could not 
initialize proxy - no Session 

我不明白为什么会发生(休眠会话时杰克逊试图序列化对象关闭),但应该不是库杰克逊的数据类型,hibernate4(其是dropwizard-hibernate的依赖项)自动为我处理这个问题(重新打开会话并实现集合)?如果不是这个库在做什么以及大多数dropwizard应用程序如何解决这个问题(EAGER抓取不是一个选项)?

的pom.xml

<dependency> 
     <groupId>io.dropwizard</groupId> 
     <artifactId>dropwizard-core</artifactId> 
     <version>0.9.2</version> 
    </dependency> 

    <dependency> 
     <groupId>io.dropwizard</groupId> 
     <artifactId>dropwizard-testing</artifactId> 
     <version>0.9.2</version> 
    </dependency> 

    <dependency> 
     <groupId>io.dropwizard</groupId> 
     <artifactId>dropwizard-hibernate</artifactId> 
     <version>0.9.2</version> 
    </dependency> 

模型

@Entity 
public class Computer { 

    @Id 
    private Long id; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    private String name; 

    @JsonIgnore 
    @OneToMany 
    public List<Part> parts; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public List<Part> getParts() { 
     return parts; 
    } 

    public void setParts(List<Part> parts) { 
     this.parts = parts; 
    } 
} 

@Entity 
public class Part { 
    @Id 
    private Long id; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 
} 

资源:

@GET 
@UnitOfWork 
@Timed 
public Response list() { 

    Computer computer = computerDAO.findById(1L); 

    Response response = Response.ok(computer.getParts()).build(); 

    return response; 
} 

DAO:

public class ComputerDAOImpl extends AbstractDAO<Computer> implements  
ComputerDAO{ 

    public ComputerDAOImpl(SessionFactory sessionFactory) { 
     super(sessionFactory); 
    } 

    public Computer findById(Long computationId) { 
     Computer computer = get(computationId); 
     return computer; 
    } 
} 

回答

0

阅读文档,这可能是由设计:

重要

的Hibernate的Session在你的资源 方法的返回值之前关闭(例如,从数据库中的人),这 意味着你的资源的方法(或DAO)负责在返回之前初始化所有延迟加载的集合等。否则, 你会得到一个LazyInitializationException抛出你的模板(或由Jackson生成的 空值)。

因此,您的代码似乎需要专门负责加载部件,而不是使用它来运行。

或者通过快速查看文档来判断,您的问题是UnitOfWork注释。这个负责关闭你的会话。阅读文档:

这会自动打开一个会话,开始一个事务,调用 findByPerson,提交事务,最后关闭会话。 如果抛出异常,则事务回滚。

与以上相结合:如果您想使用UnitOfWork,您必须自己实现延迟加载,因为UnitOfWork会在您到达之前关闭会话。如果你不想使用它,你将不得不以不同的方式处理你的交易。

我希望帮助。

Artur

相关问题