【问题标题】:Making Date queries on MongoDB using JSON on SpringDataMongoDB在 SpringDataMongoDB 上使用 JSON 在 MongoDB 上进行日期查询
【发布时间】:2019-07-03 03:57:52
【问题描述】:

在使用JHipster 创建的项目上,我在使用SpringDataMongoDB 上的@Query 注释进行MongoDB Date 查询时遇到了一些麻烦。

由于 JHipster 用于创建项目,因此大多数查询都是使用 Spring Data query builder mechanism 创建的,对于更精细的查询,而不是使用 Type-safe Query methods,我决定坚持使用 JHipster 的标准配置并制作使用@Query 注释的个性化查询,允许创建MongoDBJSON 查询。

但是,我无法在我的 Json 查询中引用 DateLocalDate 类型的任何实体字段。

我尝试采用this thread 的答案作为解决方案,但没有成功。

查询尝试

@Repository
public interface CourseClassRepository extends MongoRepository<CourseClass, String> {

    // WORKS - query with `endDate` directly constructed by Spring Data
    // This sollution however isn't enought, since 'experience_enrollments.device_id' cannot be used as a parameter
    List<CourseClass> findAllByInstitutionIdAndEndDateIsGreaterThanEqual(Long institutionId, LocalDate dateLimit);

    // Using @Query to create a JSON query doesn't work.
    // apparently data parameter cannot be found. This is weird, considering that in any other @Query created the parameter is found just fine.
    // ERROR: org.bson.json.JsonParseException: Invalid JSON input. Position: 124. Character: '?'
    @Query(" { 'experience_enrollments.device_id' : ?0, 'institution_id': ?1, 'end_date': { $gte: { $date: ?2 } } } ")
    List<CourseClass> findAllByExperienceDeviceAndInstitutionIdAndEndDate(String deviceId, Long institutionId, Date dateLimit);

    // Adopting the stackoverflow answer mentioned above also throws an error. I belive that this error is related to the fact that '?2' is being interpreted as a String value and not as reference to a parameter
    // ERROR: org.bson.json.JsonParseException: Failed to parse string as a date
    @Query(" { 'experience_enrollments.device_id' : ?0, 'institution_id': ?1, 'end_date': { $gte: { $date: '?2' } } } ")
    List<CourseClass> findAllByExperienceDeviceAndInstitutionIdAndEndDate(String deviceId, Long institutionId, Date dateLimit);

    // Even hardcoding the date parameter, the query throws an error
    // ERROR: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.time.ZonedDateTime.
    @Query(" { 'experience_enrollments.device_id' : ?0, 'institution_id': ?1, 'end_date': { '$gte': { '$date': '2015-05-16T07:55:23.257Z' } } }")
    List<CourseClass> findAllByExperienceDeviceAndInstitutionIdAndEndDate(String deviceId, Long institutionId);
}

数据库配置

@Configuration
@EnableMongoRepositories("br.com.pixinside.lms.course.repository")
@Profile("!" + JHipsterConstants.SPRING_PROFILE_CLOUD)
@Import(value = MongoAutoConfiguration.class)
@EnableMongoAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class DatabaseConfiguration {
     @Bean
        public MongoCustomConversions customConversions() {
            List<Converter<?, ?>> converters = new ArrayList<>();
            converters.add(DateToZonedDateTimeConverter.INSTANCE);
            converters.add(ZonedDateTimeToDateConverter.INSTANCE);
            return new MongoCustomConversions(converters);
        }
}

日期转换器

    public static class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {

        public static final DateToZonedDateTimeConverter INSTANCE = new DateToZonedDateTimeConverter();

        private DateToZonedDateTimeConverter() {
        }

        @Override
        public ZonedDateTime convert(Date source) {
            return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
        }
    }

    public static class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {

        public static final ZonedDateTimeToDateConverter INSTANCE = new ZonedDateTimeToDateConverter();

        private ZonedDateTimeToDateConverter() {
        }

        @Override
        public Date convert(ZonedDateTime source) {
            return source == null ? null : Date.from(source.toInstant());
        }
    }

【问题讨论】:

  • ParameterBindingJsonReader.visitDateTimeExtendedJson 中有一个错误。我打开了DATAMONGO-2315 来解决这个问题。
  • 谢谢克里斯托夫!一段时间后,我决定采用另一种解决方案,因为无法使用 MongoDBJson 进行查询。我稍后会发布我的答案并参考该错误以供将来参考。再次感谢您的宝贵时间。

标签: spring-boot mongodb-query jhipster spring-data-mongodb


【解决方案1】:

事实证明,正如Christoph Strobl 所述,该行为实际上是bug。因此,在 Spring Data MongoDB 的未来版本中不必担心这一点。在此之前,我将分享我的解决方案。

由于我无法使用 MongoDBJSon 创建查询,所以我使用了 MongoTemplate,一切都很好。

import org.springframework.data.mongodb.core.MongoTemplate;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;   

    @Autowired
    public MongoTemplate mongoTemplate;

    public List<CourseClass> findEnrolledOnExperienceDeviceWithMaxEndDateAndInstitutionId(String deviceId, LocalDate endDate, Long institutionId) {
        return mongoTemplate.find(query(
            where("experience_enrollments.device_id").is(deviceId)
                .and("institution_id").is(institutionId)
                .and("end_date").gte(endDate)), CourseClass.class);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多