2016-07-27 63 views
1

请问如何在Spring Data Mongodb中使用@Query来查找使用Date的数据?春天的数据Mongodb处理与@Query的日期

我提供我下面的代码:

仓储类:

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”,它仍然会返回2结果(上述2个文件),即使2016-07-19数据库中没有创建记录。

http://localhost:8080/projects/byCreatedDate?createdDate=2016-07-19T14:38:54.439Z

什么是上面我的代码的问题?能否请你帮忙 ?

如何更正上面的代码以处理Mongodb日期?

回答

2

我都看准这是不正确的日期格式的问题,改变了ServiceImpl类代码如下,现在的文件按预期的方式获取:

回报customerRepository.findAllCustomersByCreatedDate(新的SimpleDateFormat(“YYYY-MM- 。dd'T'HH:MM:ss.SSS'Z'原“)解析(createdDate));

0

另一种方式 -

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd"); 
LocalDate localDate = dtf.parseLocalDate(createdDate);  
Date dt = Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.UTC)); 
return customerRepository.findAllCustomersByCreatedDate(dt);