My domain object -
Person{
String name;
Date born;
}
and I have a PersonRepository
PersonRepository{
@Query(value="{'born': {$gt: new Date(?0)} }")
findPerson(Date bornAfter);
}
I'm trying to fetch all Persons born after a certain date. That doesn't work though. What am I missing? The date-format for 'born' in mongodb console looks like
ISODate("2011-11-16T09:46:33.750Z")
I tried to look for a unit/integration test for this in data-jpa source. Couldn't find any. Can someone point me to it?
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
You can safely store dates as strings and query on them as long as they are properly formatted for date, i.e., “YYYY-MM-ddTHH:mm:ss”.
Yes, DataNucleus JPA allows it, as well as to many other databases.
@Document is an annotation provided by Spring data project. It is used to identify a domain object, which is persisted to MongoDB. So you can use it to map a Java class into a collection inside MongoDB. If you don't use Spring Data, you don't need this annotation.
So first you have to make sure you don't mix up Spring Data JPA with Spring Data MongoDB here. I don't think any part of the question is actually targetting some JPA stuff. Here's how your Repository might look like:
public interface PersonRepository extends Repository<Person, Long> {
// Query generated from the method name
List<Person> findByBornGreaterThan(Date born);
@Query("{'born' : { '$gt' : ?0 }}")
List<Person> findPersons(Date born);
}
The latter does not work for 1.0.1.RELEASE and I have created a ticket for that and already fixed it for the upcoming versions 1.0.2.RELEASE and 1.1.0.M1. So you might wanna grab a snapshot build to try it. I have also created a ticket to add Before
and After
to the supported keywords for more intuitive use than LessThan
and GreaterThan
currently allow.
Either use the @Query
annotation or use the key words in the method name. I'd advise to just stick with the key words in the method name. Which means this annotation can be removed. Means,
List<Person> findByBornGreaterThan(Date born);
will only work. You can refer https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/repositories.html for more clarification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With