【发布时间】:2016-12-01 07:31:44
【问题描述】:
您能否帮助我了解如何在 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")
}
如果我使用日期字符串作为“2016-07-19T14:38:54.439Z”调用以下 URL,即使在 2016-07-19 之后没有创建记录,它仍会返回 2 个结果(超过 2 个文档)数据库。
http://localhost:8080/projects/byCreatedDate?createdDate=2016-07-19T14:38:54.439Z
我上面的代码有什么问题?你能帮忙吗?
如何更正上面的代码以使用 Mongodb 处理日期?
【问题讨论】:
标签: java spring mongodb spring-mvc spring-data