【问题标题】:What does "org.hibernate.type.CollectionType : Created collection wrapper" means?“org.hibernate.type.CollectionType:创建的集合包装器”是什么意思?
【发布时间】:2019-01-05 14:56:07
【问题描述】:

LazyLoading 似乎在我的应用程序中不起作用,我不知道为什么。

我有如下相关的实体:

public class Participant {
    private Long id;

    @OneToMany( mappedBy = "participant", fetch = FetchType.LAZY )
    private Set<RequestProduct>                  requestProducts;

    @OneToMany( mappedBy = "participant", fetch = FetchType.LAZY )
    private Set<ParticipantRank>                 participantRanks;

    @OneToMany( mappedBy = "participant", fetch = FetchType.LAZY )
    private Set<RequestProductParticipant>       requestProductParticipants;
}

还有

public class RequestProduct {
  private Long id;

  @Column
  private String identifier;       

  @ManyToOne( fetch = FetchType.LAZY )
  private Participant participant;
}

和存储库:

public interface RequestProductRepository extends JpaRepository<RequestProduct, Long> { 

 Optional<RequestProduct> findByIdentifier( String identifier );
}

以及服务方法:

@Transactional
@Service
public class ServiceImpl {
   private RequestProductRepository repo;

   public void modifyRequestProduct(String identifier){ 
    //THE PROBLEM IS HERE
    Optional<RequestProduct> product = repo.findByIdentifier( identifier );
  }
}

当我调用findByIdentifier 方法时,似乎所有数据都已加载。我有这些堆栈跟踪:

[ taskExecutor-7] org.hibernate.type.CollectionType        : Created collection wrapper: [org.module.module.models.Participant.requestProducts#1]
[ taskExecutor-7] org.hibernate.type.CollectionType        : Created collection wrapper: [org.module.module.models.Participant.participantRanks#1]
[ taskExecutor-7] org.hibernate.type.CollectionType        : Created collection wrapper: [org.module.module.models.Participant.requestProductParticipants#1]

然后调用 3 个大 select 查询,从 3 个表中的每一个加载所有数据。到底是怎么回事? 正常吗?

感谢您的解释。

【问题讨论】:

    标签: hibernate spring-data-jpa lazy-loading one-to-many many-to-one


    【解决方案1】:

    刚刚遇到这个问题并找到了解决方案。发生这种情况的原因是集合的类型为 Set。默认情况下,Java 会尝试通过检查对象的所有属性是否等于计数器对象来检查集合中是否已存在,因此它将获取所有参与者集合。

    我通过覆盖我的模型的 equalshash 方法解决了这个问题,并且只使用 ID 比较它们:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        RequestProduct requestProduct = (RequestProduct) o;
        return Objects.equals(id, requestProduct.id);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    

    抱歉迟到了将近一年=/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 2013-01-12
      • 2018-07-17
      • 2015-10-07
      • 2021-12-10
      • 1970-01-01
      • 2020-09-19
      • 2022-01-22
      相关资源
      最近更新 更多