我配置了一个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"
}
这是我的Projection界面的样子:
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的类,该类提供了make,model和modelYear数据点。但是,并非每个“用法”记录都有匹配的vehicleInfo。如果找不到匹配项,则会引发错误。
我正在寻找一种提供vehicleInfo默认值的方法。根据Spring文档,我可以做这样的事情:
@Value("#{target.vehicleInfo.make} ?: 'not available' ")
String getMake();
但这对我不起作用。 :(我仍然收到与上面引用的相同的错误。
答案 0 :(得分:3)
该错误表明vehicleInfo
本身为空,因此您需要使用安全的导航操作符。另外,方括号必须放在整个表达式周围,以便SpEL可以评估整个事情。
@Value(“#{target.vehicleInfo?.make ?: ‘not available’}“)
String getMake();