【问题标题】:Spring crud repository sorting by case insensitive stringSpring crud 存储库按不区分大小写的字符串排序
【发布时间】:2016-07-07 09:46:53
【问题描述】:


我的 crud 存储库界面是:

public interface BookRepository extends CrudRepository<BookEntity, String> {

    List<BookEntity> findByLibraryIdOrderByNumberAsc(long libraryId);
}

我想通过它们所在图书馆的 id 获取书籍实体的列表,但也按一些名为 number 的字段排序,它是一个字符串(因为它可能看起来像 'ISBN-12356'),并按升序排序,但顺序也应不区分大小写。

我假设这可以在 SQL 中使用

完成
select * from Books where libraryId = ?  order by lower(number) ASC

Spring Crud 存储库中是否有与此等效的方法,可以通过使用方法名称来实现,而不涉及本机 SQL 的具体定义?

感谢您的帮助。

【问题讨论】:

  • 为了确保我做对了,您想在不使用任何Query 注释并且只使用方法名称约定的情况下实现此功能?使用findByLibraryIdOrderByNumberAsc,您可以获得结果,但它会导致区分大小写的搜索?并且您希望它不区分大小写。是吗?

标签: spring postgresql spring-boot spring-data spring-data-jpa


【解决方案1】:

我猜你需要创建 JPQL 查询:

public interface BookRepository extends CrudRepository<BookEntity, String> {

    @Query("select books from BookEntity books where libraryId = ?1  order by lower(number) ASC")
    List<BookEntity> findByLibraryIdOrderByNumberAsc(long libraryId);
}

【讨论】:

  • 我会投赞成票,因为该解决方案仅通过“业务逻辑”公开所需的参数,而我决定使用的解决方案期望获得一个排序对象。
【解决方案2】:

我找到的解决方案是使用以下方法:

 List<BookEntity> findByBookId(long libraryId, Sort sort);

然后为了使用此方法,您可以使用如下所示的排序对象:

public static final Sort SORT_BY_NUMBER = new Sort(new Sort.Order(Sort.Direction.ASC, "number").ignoreCase());

【讨论】:

    猜你喜欢
    • 2011-07-25
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2015-01-17
    • 2016-04-02
    相关资源
    最近更新 更多