【发布时间】:2016-03-05 09:49:16
【问题描述】:
使用 dropwizard 0.9.2 和 dropwizard-hibernate 0.9.2,我正在尝试使用休眠检索由 @OneToMany 映射的集合。不幸的是,我遇到了这个异常:
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily
initialize a collection of role: com.ng.Computer.parts, could not
initialize proxy - no Session
我确实理解为什么会发生这种情况(当杰克逊尝试序列化对象时,休眠会话关闭)但库 jackson-datatype-hibernate4(它是 dropwizard-hibernate 的依赖项)不应该处理这个问题自动为我(重新打开会话并实现集合)?如果不是这个库在做什么,大多数 dropwizard 应用程序如何解决这个问题(EAGER fetching 不是一个选项)?
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;
}
道:
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;
}
}
【问题讨论】:
标签: java hibernate jackson dropwizard