【问题标题】:java stream get Spring data jpa OneToMany Collection as nulljava流获取Spring数据jpa OneToMany Collection为null
【发布时间】:2018-08-08 07:50:08
【问题描述】:
public class ValidateClaimDataEntity{
    ...
    @OneToMany(mappedBy = "claimDataEntity")
    private List<ValidateEventDataEntity> eventDataEntityList;
}

当我这样做时

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

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

我在 UT 中这样做:

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

它记录事件数据

那么,为什么函数 claimData 将 eventList 设为空???

------------------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

【问题讨论】:

  • 使用 fetchType 作为 EAGER

标签: java-8 spring-data java-stream jquery-lazyload


【解决方案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;

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多