【问题标题】:Change default sort order for Spring Data findAll() method更改 Spring Data findAll() 方法的默认排序顺序
【发布时间】:2015-03-13 11:26:31
【问题描述】:

我正在使用 Spring Data JPA,我想知道是否可以更改 Spring Data findAll() 方法使用的实体的默认排序顺序?

【问题讨论】:

  • 为此编写您自己的 JPA 查询。
  • @Andrei 是的,但如果可能的话,我想避免这种情况。
  • findAll 没有应用任何排序。如果你想改变这个,你必须扩展 SimpleJpaRepository 并覆盖 findAll 方法。请参阅Adding custom behavior to all repositories 部分。您也可以使用它来覆盖默认行为。

标签: spring jpa spring-data spring-data-jpa


【解决方案1】:

您可以通过以下方式实现:

dao.findAll(new Sort(Sort.Direction.DESC, "colName"));
// or
dao.findAll(Sort.by("colName").descending());

实现相同目的的另一种方法。使用下面的方法名:

findByOrderByIdAsc()

【讨论】:

  • 是的,这将是一个选项。但是我希望标准的 findAll() 方法使用特定的顺序。原因是我也在上面使用@Cacheable。
  • 你能不能试试这个方法名-findByOrderByIdAsc()
  • 是的,我知道我可以使用它。但我想知道通常是否可以为实体设置默认排序。我猜不是。
  • 我在上面发布的解决方案可以满足您的需求。
  • 它只做他需要的单一方法。
【解决方案2】:

您应该可以通过以下方式做到这一点:

在 spring-data 1.5+ 中,覆盖接口中的 findAll() 方法,添加 @Query 注释并在 Entity 类中创建命名查询,例如,如下所示:

实体

@Entity
@NamedQuery(name = "User.findAll", query="select u from User u order by u.address.town")
public class User{

}

存储库

public interface UserRepository extends ... <User, Long> {

    @Override
    @Query
    public Iterable<User> findAll();
}

或者,

通过创建自定义存储库实现:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

【讨论】:

    【解决方案3】:

    改为使用 PagingAndSortingRepository。 有了它,您可以添加一个查询参数 ?sort=,

    存储库:

    public interface UserRepository extends PagingAndSortingRepository<User, Long> {
      //no custom code needed
    }
    

    GET 请求:

    localhost:8080/users?sort=name,desc
    

    【讨论】:

      【解决方案4】:

      如果你想在 findAll() jpa 查询中添加 costom 查询,你可以这样做

      这里我改变了我的默认顺序

      根据我的默认顺序是主键是id

      但现在我在这里设置 id_order 来更改我的默认顺序

      模型类

      @Entity
      @Table(name = "category")
      @NamedQuery(name = "Category.findAll", query="select u from Category u order by 
      u.id_order")
      public class Category {
      
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Integer id;
      private String nameEn;
      private String nameSi;
      private String nameTa;
      private Integer id_order;
      

      存储库类

      import com.model.Category;
      import org.springframework.data.jpa.repository.Query;
      import org.springframework.data.repository.CrudRepository;
      
      import java.util.List;
      
      public interface CategoryRepository extends CrudRepository<Category, Integer> {
      
      @Override
      @Query
      public Iterable<Category> findAll();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        相关资源
        最近更新 更多