【发布时间】:2016-09-04 04:56:34
【问题描述】:
我正在使用将 POJO 存储在 MongoDB 中的 Web 服务。我想利用 Mongo 的 'expireAfterSeconds' 生存时间功能,在一段时间后清除我收藏中的旧文档。
最初我有一个使用以下 JSON 将日期发送到 REST 服务的实现:
{
"testIndex": "testIndex",
"name": "hello",
"date": "2016-05-09T11:00:39.639Z"
}
上面的代码在集合中创建了文档,加上下面的注解,10秒后删除了文档。
@Indexed (expireAfterSeconds=10)
private Date date;
实现此代码后,我决定只在 Java 端生成日期,这意味着 JSON 现在如下:
{
"testIndex": "testIndex",
"name": "hello"
}
然后我在 POJO 中有一个使用 Jackson 的 JsonCreator 的构造函数
@JsonCreator
public TTLTestVO (@JsonProperty("testIndex") String testIndex, @JsonProperty("name") String name) {
this.testIndex = testIndex;
this.createdAt = new Date();
this.name = name;
}
通过阅读文档here,我相信这应该标记在创建新对象时要使用的构造函数。 testIndex 和 name 字段像以前一样填充。然而,通过这个实现,每次我在我的 mongo 中检查文档时,日期值都是“null”。如果我将其中一个字符串值的文本更改为“来自构造函数的你好”,构造函数似乎不会被调用,因为 JSON 中包含的初始文本是添加到数据库中的内容。
POJO
`
@Document(collection = "test")public class TTLTestVO {
@Id private String _id;
@Indexed
private String testIndex;
@Indexed (expireAfterSeconds=10)
private Date createdAt;
private String name;
@JsonIgnore
public TTLTestVO() {
// default
}
@JsonCreator
public TTLTestVO (@JsonProperty("testIndex") String testIndex, @JsonProperty("name") String name) {
this.testIndex = "hello from the constructor";
this.name = name;
}
public String getId() {
return _id;
}
public void setId(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTestIndex() {
return testIndex;
}
public void setTestIndex(String testIndex) {
this.testIndex = testIndex;
}
public Date getDate() {
return createdAt;
}
public void setDate(Date date) {
this.createdAt = date;
}
`
【问题讨论】: