gpt4 book ai didi

java - Spring data Mongodb 使用 @Query 处理日期

转载 作者:行者123 更新时间:2023-11-30 02:51:11 25 4
gpt4 key购买 nike

您能帮助我了解如何在 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,它仍然返回 2 个结果(以上 2 个文档),即使 2016-07-19 之后没有创建记录数据库。

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

我上面的代码有什么问题?你能帮忙吗?

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

最佳答案

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

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

关于java - Spring data Mongodb 使用 @Query 处理日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38610411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com