我对使用 Spring MVC 3.1.2 和 Jackson 2 的错误感到抓狂。
我有以下模型类:
@Entity
@Table(name = "USER")
@JsonIgnoreProperties(ignoreUnknown=true)
public class User implements Serializable
{
@Id
@SequenceGenerator(name = "USER_ID", sequenceName = "USER_ID_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_ID")
private Long id;
@Column(length = 50, nullable = false)
private String firstName;
@Column(length = 50, nullable = false)
private String lastName;
@ManyToMany
@JoinTable(name = "FRIENDS",
joinColumns = @JoinColumn(name = "personId"),
inverseJoinColumns = @JoinColumn(name = "friendId")
)
@JsonManagedReference
private List<User> friends;
@ManyToMany
@JoinTable(name="FRIENDS",
joinColumns=@JoinColumn(name="friendId"),
inverseJoinColumns=@JoinColumn(name="personId")
)
@JsonIgnore
private List<User> friendOf;
// Other attributes and methods...
}
当我得到一个 User 实例时,它被 Jackson 正确序列化。但是当我尝试获取包含朋友的 User 实例时,会引发以下异常:
org.hibernate.LazyInitializationException:未能延迟初始化角色集合:com.frooid.model.User.friends,没有会话或会话已关闭
我正在使用单个 HQL 获取此实例:
select u from User u left join fetch u.friends f where u.id = :id
谢谢大家!