org.hibernate.LazyInitializationException:使用Javers时无法延迟初始化角色集合

时间:2019-10-17 10:51:22

标签: java hibernate spring-boot spring-data-jpa javers

我遇到了错误: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.fleetx.persistence.model.Account.users, could not initialize proxy - no Session

当我尝试对要使用Javers进行审核的实体之一进行创建操作时。以下是我的应用程序的结构:

AudityEntity.java

@Data
@Entity
@Table
public class AuditEntity extends Base {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "account_id", updatable = false)
    @JsonIgnore
    private Account account;

    // other fields
}

Account.java

@Data
@Entity
@Table
public class Account extends Base {
    @OneToMany(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JsonIgnore
    private List<User> users;

    // other fields
}

AuditEntityRepository.java

@JaversSpringDataAuditable
public interface AuditEntityRepository extends JpaRepository<AuditEntityRepository, Long> {
    // crud operations
}

我不想将private Account account;private List<User> users;的获取类型更改为FetchType.EAGER

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

如果您不想更改为FetchType.EAGER,那么您访问Account.getUsers()的任何地方都必须处于事务中,这样就不会丢弃休眠会话。最简单的方法是将@Transactional添加到完成获取和getUsers()访问的服务或bean的方法中。确保使用@EnableTransactionManagement打开了事务。