java - Spring数据存储库: "find" method with orderBy gets the wrong order

标签 java spring-boot spring-data spring-data-jpa jpql

我有一个带有一些 JPA 存储库的 Spring Boot 应用程序。 我在存储库接口(interface)之一中定义了以下方法:

    public List<Post> findAllByOrderByPublishedOnDesc();

很明显,我想检索按 publishOn DESC 排序的所有 Post 列表。奇怪的是,当两个或多个帖子的值 publishedOn 仅在 LocalDateTime 类的分钟部分不同时,我会得到错误的顺序(请参阅下面代码中的注释)。 我做错了什么?

这是示例代码。使用H2数据库执行测试:

实体:

    @Entity
    public class Post
    {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        Long id;

        @Column(unique = true, nullable = false)
        String sourceUrl;

        @Column
        String title;

        @Column
        LocalDateTime publishedOn;

        @LastModifiedDate
        LocalDateTime editedOn;

        @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        Text text;
    }

存储库:

    public interface PostRepository extends JpaRepository<Post, Long>
    {
        public Post findBySourceUrl(String sourceUrl);
        public List<Post> findAllByOrderByPublishedOnDesc();
    }

测试:

    public class OrderByJPATest
    {
    @Autowired
    PostRepository postRepo;

    public OrderByJPATest()
    {
    }

    @Test
    public void testOrderByDays()
    {
            // First try: older by 1 day
            Post newer = insertTestEntity("newer", LocalDateTime.of(2016, 11, 13, 0, 0));
            Post older = insertTestEntity("older", LocalDateTime.of(2016, 11, 12, 0, 0));

            List<Post> ordered = postRepo.findAllByOrderByPublishedOnDesc();

            ordered.stream().forEach((post) -> log.info("{} => {}", post.getSourceUrl(), post.getPublishedOn()));

            /*
            output:
            newer => 2016-11-13T00:00
            older => 2016-11-12T00:00
            */

            assertTrue(ordered.get(0).getPublishedOn()
                    .isAfter(ordered.get(1).getPublishedOn()));

            postRepo.deleteAll();
            postRepo.flush();

            // Second try: older by 1 minute
            newer = insertTestEntity("newerBy1Min", LocalDateTime.of(2016, 11, 13, 01, 02));
            older = insertTestEntity("olderBy1Min", LocalDateTime.of(2016, 11, 13, 01, 01));

            ordered = postRepo.findAllByOrderByPublishedOnDesc();

            ordered.stream().forEach((post) -> log.info("{} => {}", post.getSourceUrl(), post.getPublishedOn()));

            /* 
            output:
            olderBy1Min => 2016-11-13T01:01
            newerBy1Min => 2016-11-13T01:02
            */

            // this assert fails!
            assertTrue(ordered.get(0).getPublishedOn()
                    .isAfter(ordered.get(1).getPublishedOn()));
    }

    private Post insertTestEntity(String url, LocalDateTime publishDate)
    {
            Text text = new Text();
            text.setValue("Testing...");
            Post post = new Post();
            post.setPublishedOn(publishDate);
            post.setSourceUrl(url);
            post.setText(text);

            return postRepo.save(post);
    }
    }

POM(依赖项):

   <dependencies>

        <dependency>
            <groupId>com.atlassian.commonmark</groupId>
            <artifactId>commonmark</artifactId>
            <version>0.6.0</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <!--Additional dependencies -end-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

最佳答案

JPA 默认情况下会将 Java 的 LocalDateTime 映射到 BLOB,而不是 DateTimeTimestamp

数据库不理解如何对 BLOB 执行日期/时间排序。

  1. 确保使用适当的数据类型创建架构(使用 @Column 注释或使用 SQL 脚本)。
  2. hibernate-java8 依赖项添加到您的项目

执行上述步骤后,将发生正确的排序。

关于java - Spring数据存储库: "find" method with orderBy gets the wrong order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616629/

相关文章:

java - 非最终字段的同步

java - 请帮助我解决 Spring Boot 2 中的错误,

spring - 处理 UserRedirectRequiredException(需要重定向才能获得用户批准)

hibernate - JPA by kotlin : by lazy and @Transient not work with hibernate

java - 服务器-客户端应用程序中的 Spring Data 分页

spring - Spring Data REST 的 QueryDSL 集成可以用来执行更复杂的查询吗?

java - W/TextToSpeech : speak failed: not bound to TTS engine

java 美元符号 com.package.Foo.$$$.Bar 问题

java - 如何使用 Apache HttpClient 4 获取文件上传的进度条?

java - Spring HATEOAS 1.0,删除了 BaseUriLinkBuilder