在一次项目开发中,当某个字段的值是另外一个表的主键时,如果通过把该字段的值放入能过字键查询,这时如果字段的值为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);
}
在此记下,以免以后再走坑!