spring - 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();
但这对我不起作用。:( 我仍然得到与上面引用的相同的错误。
解决方案
该错误表明它vehicleInfo
本身为空,因此您需要使用安全导航运算符。此外,括号需要围绕整个表达式,以便 SpEL 将评估整个事物。
@Value(“#{target.vehicleInfo?.make ?: ‘not available’}“)
String getMake();
推荐阅读
- google-drive-api - https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable。如何找到文件id
- flask - 为什么 gunicorn 从不同的目录运行模块?
- sql - 对于 d 中 c 行中的每个值,返回最大值为 a 的行
- java - 遍历对象的arraylist并返回每个类属性
- angular - 使用 FormArray 在运行时创建表单控件
- python - 通过多处理和shutil python从目录复制文件
- c - 为什么我没有收到来自内核的消息?
- curl - 使用 curl 请求将变量添加到函数节点中
- php - bind_param 函数没有做任何事情
- python - 如何从两个列表列表在python中创建一个字典