我有一个简单的控制器返回一个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.但可能通过新的杰克逊功能可以实现.
我的版本是:
提前致谢.
在尝试序列化作为JPA实体的ESRBRating对象时,我遇到了两个不同的堆栈跟踪(见下文).我正在使用Spring Data JPA.控制器调用服务,称为存储库的服务.我能够通过在我的ESRBRating对象上添加@Proxy(lazy = false)来解决此问题.
我的主要问题是@Proxy(lazy = false)实际上做了什么?添加时为什么会起作用?这是一个很好的解决方案,还是会产生诸如性能/内存问题等副作用?
作为参考,这是我的ESRBRating课程.
@Entity
@Table(name = "esrb_rating", schema = "igdb")
@JsonIgnoreProperties(ignoreUnknown = true)
@Proxy(lazy = false)
public class ESRBRating implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Long id;
@NotNull
@Size(min = 1, max = 255)
@Column(name = "title", nullable = false, length = 255)
private String title;
@Size(max = 65535)
@Column(length = 65535)
private String description;
@OneToMany(cascade = CascadeType.ALL, …Run Code Online (Sandbox Code Playgroud)