java stream获取Spring数据jpa OneToMany Collection为null

问题描述 投票:0回答:1
public class ValidateClaimDataEntity{
    ...
    @OneToMany(mappedBy = "claimDataEntity")
    private List<ValidateEventDataEntity> eventDataEntityList;
}

当我做

function(ValidateClaimDataEntity claimDataEntity){
   claimDataEntity
            .getEventDataEntityList().parallelStream()....
}

我得到零点异常,我调试了claimDataEntity .getEventDataEntityList()是null但实际上这个claimDataEntity在db中有相关的事件数据

我在UT这样做:

claimDataEntityRepository.findById(32L).get().getEventDataEntityList().parallelStream().forEach(eventDataEntity -> {
            log.info(eventDataEntity.getValidateEventDataId());
        });

它记录事件数据

那么,为什么函数claimData得到eventList为null ???

-------------------- v1 ----------------------------- -----------

我发现它可能不是流的问题,实际上我在迭代器之前做了一个保存

public ValidateClaimResponse bc(ValidateClaimRequest claimRequest) {

        //claim
        ValidateClaimDataEntity claimDataEntity = new ValidateClaimDataEntity(claimRequest);
        claimDataEntityRepository.save(claimDataEntity);

        claimRequest.getEventRequestList()
                .forEach(eventRequest -> {
                    ...

                    //event
                    ValidateEventDataEntity eventDataEntity = new ValidateEventDataEntity(eventRequest);
                    eventDataEntity.setValidateClaimDataId(claimDataEntity.getValidateClaimDataId());

                    eventDataEntityRepository.save(eventDataEntity);
                });


    System.out.println(claimDataEntity.getEventDataEntityList() == null ? "null" : claimDataEntity.getEventDataEntityList() );

    ValidateClaimDataEntity claimDataEntity2 = claimDataEntityRepository.findById(claimDataEntity.getValidateClaimDataId()).get();
    System.out.println(claimDataEntity2.getEventDataEntityList() == null ? "null2" : claimDataEntity2.getEventDataEntityList());

我得到了eventList的null

java-8 spring-data java-stream jquery-lazyload
1个回答
1
投票

@OneToMany的默认fetchtype是LAZY(Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate)。因此它没有取得。让它EAGER

@OneToMany(mappedBy = "claimDataEntity", fetch = FetchType.EAGER)
private List<ValidateEventDataEntity> eventDataEntityList;
© www.soinside.com 2019 - 2024. All rights reserved.