记一次Spring data通过主键(索引)查询,当主键(索引)值为空时的问题

在一次项目开发中,当某个字段的值是另外一个表的主键时,如果通过把该字段的值放入能过字键查询,这时如果字段的值为null或者为“”时,当请求查询时前端会报“The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!”
查询场景:

JkCommodity jkCommodity=jkCommodityRepository.findById(jkJackpotPrize.getPrizeId()).orElseGet(JkCommodity::new);

getPrizeId() :如果得到的值是空的,那么此时查询就会报错“The given id must not be null”,能过查看findById()源代码发现,其传进来的id是不能空的。
SimpleJpaRepository findById()源码:

public Optional<T> findById(ID id) {
        Assert.notNull(id, "The given id must not be null!");
        Class<T> domainType = this.getDomainClass();
        if (this.metadata == null) {
            return Optional.ofNullable(this.em.find(domainType, id));
        } else {
            LockModeType type = this.metadata.getLockModeType();
            Map<String, Object> hints = this.getQueryHints().withFetchGraphs(this.em).asMap();
            return Optional.ofNullable(type == null ? this.em.find(domainType, id, hints) : this.em.find(domainType, id, type, hints));
        }
    }

KeyValueTemplate findById()源码:

public <T> Optional<T> findById(Object id, Class<T> type) {
        Assert.notNull(id, "Id for object to be inserted must not be null!");
        Assert.notNull(type, "Type to fetch must not be null!");
        String keyspace = this.resolveKeySpace(type);
        this.potentiallyPublishEvent(KeyValueEvent.beforeGet(id, keyspace, type));
        T result = this.execute((adapter) -> {
            Object value = adapter.get(id, keyspace, type);
            return value != null && !typeCheck(type, value) ? null : type.cast(value);
        });
        this.potentiallyPublishEvent(KeyValueEvent.afterGet(id, keyspace, type, result));
        return Optional.ofNullable(result);
    }

在此记下,以免以后再走坑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值