自定义Spring Data Rest投影

时间:2017-11-06 17:45:19

标签: java spring jackson spring-data-rest spring-hateoas

我有一个Date字段的实体:

@NotNull
@Temporal(TemporalType.TIMESTAMP) // this annotation impacts on result
@JsonFormat(pattern = DATE_FORMAT)
@Column(name = "my_time", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Date myTime;

我对该字段有一个预测:

@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
String getMyTime();

这是我的java代码:

@Autowired
private ProjectionFactory projectionFactory;

....
public PagedResources<Resource<MyEntityProjection>> transform(final Page<MyEntity> page) {
    return assembler.toResource(page, entity -> {
        final MyEntityProjection projected = projectionFactory.createProjection(MyEntityProjection.class, entity);
        return new Resource<>(projected, <some links>);
    });
}

当我尝试在java代码中为此实体创建投影时,我在JSON中收到以下格式:

"myTime": "2017-07-27"

如何修复它以yyyy-MM-dd'T'HH:mm:ss.SSSZ格式接收日期?

1 个答案:

答案 0 :(得分:1)

最后,我找到了一个解决方案:

只需在Projection界面中为您的字段添加注释;

import com.fasterxml.jackson.annotation.JsonFormat;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
Date getMyDate();