你能帮我解决一下如何在Spring Data Mongodb中使用@Query来查找使用Date的数据吗?
我在下面提供了我的代码:
存储库类:
public interface CustomerRepository extends MongoRepository<Customer, String> {
@Query("{ 'createdDateTime' : { $gt: ?0 } }")
List<Customer> findAllCustomersByCreatedDate(Date date);
}
ServiceImpl类:
@Service("CustomerService")
public class CustomerServiceImpl implements CustomerService {
public List<Customer> findAllCustomersByCreatedDate(String createdDate) throws ParseException {
return customerRepository.findAllCustomersByCreatedDate(new SimpleDateFormat("YYYY-MM-DD").parse(createdDate));
}
}
RestController类:
@RestController
@RequestMapping("customers")
public CustomerController {
@Autowired
private CustomerService customerService;
@RequestMapping(value = "/byCreatedDate", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
public ResponseEntity<List<Customer>> findAllCustomersByCreatedDate(@RequestParam String createdDate)
throws BusinessException, ParseException {
List<Customer> customers = customerService.findAllCustomersByCreatedDate(createdDate);
return ResponseEntity.status(HttpStatus.OK).body(customers);
}
}
Mongo数据库中的数据供客户收集:
{ "_id" : ObjectId("57851d1ee59782560e77ac3f"),
"_class" : "com.myproject.models.Customer",
"name" : "Rob",
"createdBy" : "John",
"createdDateTime" : ISODate("2016-07-12T16:38:54.439Z")
}
{ "_id" : ObjectId("5786222b29b42251b16b5233"),
"_class" : "com.myproject.models.Customer",
"name" : "Sara",
"createdBy" : "John",
"createdDateTime" : ISODate("2016-07-13T08:38:52.116Z")
}
如果我使用日期字符串调用以下URL作为“2016-07-19T14:38:54.439Z”,即使2016-07-19之后没有创建记录,它仍会返回2个结果(超过2个文档)数据库中。
http://localhost:8080/projects/byCreatedDate?createdDate=2016-07-19T14:38:54.439Z
上面的代码有什么问题?你能帮忙吗?
如何更正上面的代码以处理Mongodb的日期?
答案 0 :(得分:2)
我发现问题是日期格式不正确,并更改了ServiceImpl类代码,如下所示,现在按预期获取文档:
返回customerRepository.findAllCustomersByCreatedDate(new SimpleDateFormat(“yyyy-MM-dd'T'HH:mm:ss.SSS'Z'”)。parse(createdDate));
答案 1 :(得分:0)
另一种方式 -
AND ''='