我已经按照Spring.io上的指南使用rest访问MongoDB数据(https://spring.io/guides/gs/accessing-mongodb-data-rest/),并能够将文档保存到mongo中。当我尝试在POJO中添加日期字段并将日期设置为
我创建了一个非常基本的
我可以将日期保存为字符串到Mongo中,但我想要的是能够以日期格式保存日期,以便可以使用基本的“日期 between”查询查询它们(所以类似这样的内容,确切的格式并不重要-
最简单的方法是什么?
编辑:
Pojo class -
new Date()
对象时,保存到mongo时它只会把这个值保存为null。我创建了一个非常基本的
@RestController
,它运行良好(通过请求体进行传递,并使用我的MongoRepository
类保存下来),可以通过rest控制台保存文档。我尝试在此处创建一个新的日期,并在保存之前将其设置,但是这会给我一些像"createdDate": 1472394366324
这样的东西。我可以将日期保存为字符串到Mongo中,但我想要的是能够以日期格式保存日期,以便可以使用基本的“日期 between”查询查询它们(所以类似这样的内容,确切的格式并不重要-
"date": ISODate("2014-02-10T10:50:42.389Z")
)。我可以编写用于通过参数获取值的查询,但是要使“日期between”查询工作,我需要能够将日期值存储到Mongo中。最简单的方法是什么?
编辑:
Pojo class -
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Document(collection = "Musicians")
public class Musician {
@Id
private String id;
private String firstName;
private String lastName;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdDate = new Date();
public Musician() {}
public Musician(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
//createdDate = new Date();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
The RestController class -
@RestController
@RequestMapping(value = "/musicians")
public class MusicianController {
@Autowired
MusicianRepository musicianRepository;
@Autowired
MongoTemplate mongoTemplate;
@RequestMapping(method = RequestMethod.POST, value = "")
public ResponseEntity<HttpStatus> createMusician(@RequestBody Musician musician) {
Musician musicianIn = musician;
musicianRepository.save(musicianIn);
return new ResponseEntity(HttpStatus.ACCEPTED);
}
@RequestMapping(method = RequestMethod.GET, value = "")
public ResponseEntity<List<Musician>> getMusicians() {
List<Musician> musicians = musicianRepository.findAll();
return new ResponseEntity<List<Musician>>(musicians, HttpStatus.OK);
}
}
@CreatedDate
注解,例如:class MyObject{ @CreatedDate Date date; } - ypriverol