java - Hibernate 5.2.11 - 多个同时 Featch.Eager

标签 java hibernate jpa

我有一个类女巫有 4 个带有 @*toMany 注释的列表:

    public class Component {

            @OneToMany(mappedBy = "component", orphanRemoval = true, cascade = CascadeType.ALL, targetEntity = ComponentHistoric.class)
            //@OnDelete(action = OnDeleteAction.CASCADE)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<ComponentHistoric> componentHistoricList;

            @ManyToMany(targetEntity = Organization.class)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<Organization> organizations;

            @OneToMany(targetEntity = ComponentPerson.class, cascade = CascadeType.ALL)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<ComponentPerson> componentPeople;

            @OneToMany(targetEntity = ComponentLink.class, cascade = CascadeType.ALL)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<ComponentLink> componentLinks;
    }

不可能使用Set<>而不是 Lists 。当我使用featch = Featch.Eager时。我得到了异常(exception)(第 1 号)。上面的当前版本出现了异常(编号 2)。

Exception (Number 1): org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

-

Exception (Number 2): org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxxx.xxxxx.xxxx.ComponentHistoric.componentHistoricVersion, could not initialize proxy - no Session

最佳答案

异常编号 1:

这是 Hibernate 的一项限制,它不支持在一个实体中多个预先加载的列表。

异常编号 2:

当在事务边界之外访问您的列表时,您会收到此异常。因此,您必须在使用该集合之前对其进行初始化。

有很多选项可以做到这一点:

  • 在集合上调用 getter 或迭代器
  • 使用 Hibernate.initialize() 并将集合作为参数传递
  • 通过查询加载实体时,在查询中使用连接提取

关于java - Hibernate 5.2.11 - 多个同时 Featch.Eager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47480519/

相关文章:

java - 无法在屏幕上显示输出

java - 为什么 toString 不允许 throws 子句

spring - 在使用 liquibase 填充数据库后,如何更正 Postgres 序列?

java - 我应该 try catch 任何 EnityManager 查询异常吗?

java - JPA:两个实体之间存在多个多对多关系?

javac 版本和 java 版本在命令行上显示不同

java - 使用 jpa 和 hibernate 的 Spring Security

java - 如何使用基于Java的配置解决Spring MVC中的 "noHandlerFound"?

multithreading - Spring @Async 和 AbstractRoutingDataSource

java - 如何在 spring hibernate 中加入表