我正在使用 Spring 和 JPA(带有 MySQL 的 Hibernate)以及 Lombok。
您好,我的实体的这一部分:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "entitya")
public class EntityA implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ea_id")
Long id;
....
@ManyToOne
@JoinColumn(name="g_id", nullable=false)
private Group group;
....
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "group")
public class Group implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="g_id")
private Long id;
@OneToMany(mappedBy="group")
private List<EntityA> enitiesA = new ArrayList<>();
...
}
我还实现了存储库扩展 JPARepository。 在我的 Controller 中,如果我尝试通过 Id 检索 EntityA,我会收到此异常:
failed to lazily initialize a collection of role: com.mytest.entity.Group.enitiesA, could not initialize proxy - no Session
对我来说这很奇怪,因为我只需要检索对象。我对此没有使用一些 getter 方法。因此,理论上,使用默认的获取类型,我不需要组列表。
出了什么问题?
最佳答案
您是否使用 toString() 调试对象?
如果可能是@Data注解引起的错误。
生成的 toString() 方法包含所有字段,因此它可能会调用 enitiesA 变量,从而产生延迟初始化错误。
https://mdeinum.github.io/2019-02-13-Lombok-Data-Ojects-Arent-Entities/
关于java - 无法延迟初始化角色集合。简单的 JPA findById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60995589/