I've followed the Spring.io guide for accessing MongoDB data with rest (https://spring.io/guides/gs/accessing-mongodb-data-rest/) and can save documents into mongo.
When I try to add a date field into the POJO and set the date as a new Date() object, it just saves the value as null when it saves to mongo.
I've created an extremely basic @RestController which is working fine (passes in the request body, and saves it down using my MongoRepository class), saving documents via the rest console. I tried creating a new date in here and setting it before saving it down to Mongo but this gives me something like "createdDate": 1472394366324.
I can save dates as a string into Mongo, but what I want is to be able to save dates in the date format so I can query them with a basic 'date between' query (so something like this, the exact format doesn't matter much - "date" : ISODate("2014-02-10T10:50:42.389Z"). I can write the queries to get values via parameters, but to get the 'date between' query working I need to be able to store date values into Mongo.
What is the easiest way to accomplish this?
Edit:
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);
}
}
@CreatedDateannotation to the attribute of your POJO for example: class MyObject{ @CreatedDate Date date; }