【发布时间】:2018-02-12 21:19:36
【问题描述】:
我有带有异步端点的 Spring MVC 应用程序:
@GetMapping
public DeferredResult<Collection<B>> get() {
DeferredResult<Collection<B>> result = new DeferredResult<>();
Executors.newSingleThreadExecutor().submit(() -> result.setResult(service.getB()));
return result;
}
我正在尝试使用jackson-datatype-hibernate 序列化惰性对象:
@Entity
@Table
public class B {
@Id
@GeneratedValue
private UUID id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id")
private A a;
public A getA() {
return a;
}
}
但我得到了:
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.example.demo.B["a"])
【问题讨论】:
-
错误与
Hibernate Session有关,与HTTP Session无关;基本上,您还试图整理B类的A a属性,因为您有Lazy获取策略,您会收到错误 -
@AngeloImmediata 实际上,当我不尝试在新线程中执行任务时,它适用于 Callable 或 CompletableFuture。我使用 com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module 添加了带有自定义 ObjectMapper 的 bean MappingJackson2HttpMessageConverter。
-
这很奇怪..错误很清楚,提取策略总是很清楚。您是否检查过它工作时的所有参数是否与不工作的测试相同?
-
@AngeloImmediata 是的,它绝对适用于 Callable 或仅适用于 Collection,即使没有 Eager fetch 类型或 JsonIgnore。
-
所以最可能的原因是故障答案中指出的原因
标签: spring hibernate jackson threadpool lazy-evaluation