2016-07-27 57 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);