我有一个简单的控制器返回一个User对象,这个用户的属性坐标有hibernate属性FetchType.LAZY.
当我尝试获取此用户时,我总是必须加载所有坐标以获取用户对象,否则当Jackson尝试序列化时,用户会抛出异常:
com.fasterxml.jackson.databind.JsonMappingException:无法初始化代理 - 没有会话
这是因为杰克逊试图获取这个未被攻击的对象.这是对象:
public class User{
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
@JsonManagedReference("user-coordinate")
private List<Coordinate> coordinates;
}
public class Coordinate {
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
@JsonBackReference("user-coordinate")
private User user;
}
Run Code Online (Sandbox Code Playgroud)
和控制器:
@RequestMapping(value = "/user/{username}", method=RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String username) {
User user = userService.getUser(username);
return user;
}
Run Code Online (Sandbox Code Playgroud)
有办法告诉杰克逊不要序列化未被攻击的物体吗?我一直在寻找3年前发布的其他答案实现jackson-hibernate-module.但可能通过新的杰克逊功能可以实现.
我的版本是:
提前致谢.