【问题标题】:Spring data Mongodb handling dates with @QuerySpring data Mongodb 使用@Query 处理日期
【发布时间】: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


    【解决方案1】:

    我发现了日期格式不正确的问题,并将 ServiceImpl 类代码更改如下,现在文档按预期获取:

    return customerRepository.findAllCustomersByCreatedDate(
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(createdDate)
    );
    

    【讨论】:

      【解决方案2】:

      另一种方式——

      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);
      

      【讨论】:

        猜你喜欢
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-14
        • 2014-11-28
        • 1970-01-01
        • 2017-09-05
        相关资源
        最近更新 更多