首页 > 解决方案 > Spring Data REST 投影值的默认值?

问题描述

我配置了 Spring Data REST 投影,当可以找到相关数据时,它按预期工作。但是当没有找到相关数据时,会抛出如下错误:

{
"timestamp": 1532021102433,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.http.converter.HttpMessageNotWritableException",
"message": "Could not write JSON document: EL1007E: Property or field 'model' cannot be found on null (through reference chain: org.springframework.hateoas.PagedResources[\"_embedded\"]->java.util.Collections$UnmodifiableMap[\"processed\"]->java.util.ArrayList[0]->org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$ProjectionResource[\"content\"]->com.sun.proxy.$Proxy122[\"model\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: EL1007E: Property or field 'model' cannot be found on null (through reference chain: org.springframework.hateoas.PagedResources[\"_embedded\"]->java.util.Collections$UnmodifiableMap[\"processed\"]->java.util.ArrayList[0]->org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$ProjectionResource[\"content\"]->com.sun.proxy.$Proxy122[\"model\"])",
"path": "/processed/search/findByCompCode"
}

这是我的投影界面的样子:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;

import java.util.Date;

@Projection(name = "usage-detail", types = {Usage.class})
interface UsageProjection {
String getUuid();
String getProduct();
Date getReportDate();
String getVin();

@Value("#{target.vehicleInfo.make}")
String getMake();

@Value("#{target.vehicleInfo.model}")
String getModel();

@Value("#{target.vehicleInfo.modelYear}")
Integer getModelYear();
}

“vehicleInfo”是来自主要 Usage 类的一个字段,它有一个 @ManyToOne 连接到另一个名为 VehicleInfo 的类,该类提供品牌、型号和 modelYear 数据点。但是,并非每个使用记录都具有匹配的车辆信息。如果找不到匹配项,则会引发错误。

我正在寻找一种为车辆信息提供默认值的方法。根据 Spring 文档,我可以这样做:

@Value("#{target.vehicleInfo.make} ?: 'not available' ")
String getMake();

但这对我不起作用。:( 我仍然得到与上面引用的相同的错误。

标签: springspring-data-jpaspring-data-rest

解决方案


该错误表明它vehicleInfo本身为空,因此您需要使用安全导航运算符。此外,括号需要围绕整个表达式,以便 SpEL 将评估整个事物。

@Value(“#{target.vehicleInfo?.make ?: ‘not available’}“)
String getMake();

推荐阅读