“ org.hibernate.type.CollectionType:创建的集合包装器”是什么意思?

时间:2018-07-28 22:11:49

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

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方法时,似乎所有数据都已加载。我有这些stacktrace:

[ 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个表中的每一个加载所有数据。到底是怎么回事? 正常吗?

感谢您的解释。

1 个答案:

答案 0 :(得分:0)

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

我通过覆盖模型的 equals hash 方法并仅使用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);
}

很抱歉延迟了将近一年= /

相关问题