更改 Spring Data findAll() 方法的默认排序顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29031028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change default sort order for Spring Data findAll() method
提问by Marcel Overdijk
I'm using Spring Data JPA and I wonder if it is possible to change the default sort order for a entity being used by the Spring Data findAll()
method?
我正在使用 Spring Data JPA,我想知道是否可以更改 Spring DatafindAll()
方法使用的实体的默认排序顺序?
采纳答案by Alan Hay
You should be able to do this by either:
您应该可以通过以下任一方式执行此操作:
in spring-data 1.5+, overriding the findAll() method in your Interface, adding the @Query annotation and creating a named Query in your Entity class like, for example, below:
在 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{
}
Repository
存储库
public interface UserRepository extends ... <User, Long> {
@Override
@Query
public Iterable<User> findAll();
}
or,
或者,
by creating a custom repository implementation:
通过创建自定义存储库实现:
回答by Mithun
You can achieve this as follows:
您可以通过以下方式实现此目的:
dao.findAll(new Sort(Sort.Direction.DESC, "colName"));
// or
dao.findAll(Sort.by("colName").descending());
Another way to achieve the same. Use the below method name:
另一种实现相同的方法。使用以下方法名称:
findByOrderByIdAsc()
回答by Matthias
Use a PagingAndSortingRepository instead. With that in place you can add a queryparameter ?sort=,
请改用 PagingAndSortingRepository。有了这个,你可以添加一个查询参数 ?sort=,
Repository:
存储库:
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
//no custom code needed
}
GET Request:
获取请求:
localhost:8080/users?sort=name,desc
回答by Mewan
If you want to add costom query to findAll() jpa query you can do it this way
如果您想将 costom 查询添加到 findAll() jpa 查询,您可以这样做
here i changed my default order
在这里我改变了我的默认顺序
According to my default order is primary key it is id
根据我的默认顺序是主键,它是 id
but now i here set id_order to change my default order
但现在我在这里设置 id_order 来更改我的默认顺序
Model class
模型类
@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;
Repository class
存储库类
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();