如何在 Spring Data 中使用 OrderBy 和 findAll
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25486583/
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
How to use OrderBy with findAll in Spring Data
提问by Prashant Shilimkar
I am using spring data and my DAO looks like
我正在使用 spring 数据,我的 DAO 看起来像
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllOrderByIdAsc(); // I want to use some thing like this
}
In above code, commented line shows my intent. Can spring Data provides inbuilt functionality to use such a method to find all records order by some column with ASC/DESC?
在上面的代码中,注释行显示了我的意图。spring Data 是否可以提供内置功能来使用这种方法通过 ASC/DESC 查找某个列的所有记录顺序?
回答by Sikor
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public List<StudentEntity> findAllByOrderByIdAsc();
}
The code above should work. I'm using something similar:
上面的代码应该可以工作。我正在使用类似的东西:
public List<Pilot> findTop10ByOrderByLevelDesc();
It returns 10 rows with the highest level.
它返回具有最高级别的 10 行。
IMPORTANT:Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:
重要提示:因为有人告诉我很容易错过这个答案的关键点,这里有一点澄清:
findAllByOrderByIdAsc(); // don't miss "by"
^
回答by Paul Samsotha
AFAIK, I don't think this is possible with a direct method naming query. You can however use the built in sorting mechanism, using the Sortclass. The repository has a findAll(Sort)method that you can pass an instance of Sortto. For example:
AFAIK,我认为直接方法命名查询是不可能的。但是,您可以使用类使用内置的排序机制Sort。存储库有一个findAll(Sort)方法,您可以将其实例传递Sort给。例如:
import org.springframework.data.domain.Sort;
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(sortByIdAsc());
}
private Sort sortByIdAsc() {
return new Sort(Sort.Direction.ASC, "id");
}
}
回答by shlomi33
Please have a look at the Spring Data JPA - Reference Documentation, section 5.3. Query Methods, especially at section 5.3.2. Query Creation, in "Table 3. Supported keywords inside method names" (links as of 2019-05-03).
请查看Spring Data JPA - 参考文档,第 5.3 节。查询方法,特别是在第5.3.2 节。查询创建,在“表 3. 方法名称中支持的关键字”(链接截至 2019-05-03)。
I think it has exactly what you need and same query as you stated should work...
我认为它正是您所需要的,并且与您所说的相同的查询应该可以工作...
回答by TizonDife Villiard
Simple way:
简单的方法:
repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));
回答by Narayan Yerrabachu
Yes you can sort using query method in Spring Data.
是的,您可以使用 Spring Data 中的查询方法进行排序。
Ex:ascending order or descending order by using the value of the id field.
例如:使用 id 字段的值进行升序或降序。
Code:
代码:
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllByOrderByIdAsc();
}
alternative solution:
替代解决方案:
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(orderByIdAsc());
}
private Sort orderByIdAsc() {
return new Sort(Sort.Direction.ASC, "id")
.and(new Sort(Sort.Direction.ASC, "name"));
}
}
Spring Data Sorting: Sorting
Spring 数据排序:排序
回答by S. FRAJ
I try in this example to show you a complete example to personalize your OrderBy sorts
我尝试在这个例子中向你展示一个完整的例子来个性化你的 OrderBy 排序
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.data.domain.Sort;
/**
* Spring Data repository for the User entity.
*/
@SuppressWarnings("unused")
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List <User> findAllWithCustomOrderBy(Sort sort);
}
you will use this example : A method for build dynamically a object that instance of Sort :
您将使用此示例:一种动态构建对象的方法,该对象是 Sort 的实例:
import org.springframework.data.domain.Sort;
public class SampleOrderBySpring{
Sort dynamicOrderBySort = createSort();
public static void main( String[] args )
{
System.out.println("default sort \"firstName\",\"name\",\"age\",\"size\" ");
Sort defaultSort = createStaticSort();
System.out.println(userRepository.findAllWithCustomOrderBy(defaultSort ));
String[] orderBySortedArray = {"name", "firstName"};
System.out.println("default sort ,\"name\",\"firstName\" ");
Sort dynamicSort = createDynamicSort(orderBySortedArray );
System.out.println(userRepository.findAllWithCustomOrderBy(dynamicSort ));
}
public Sort createDynamicSort(String[] arrayOrdre) {
return Sort.by(arrayOrdre);
}
public Sort createStaticSort() {
String[] arrayOrdre ={"firstName","name","age","size");
return Sort.by(arrayOrdre);
}
}
回答by J.Wincewicz
Combining all answers above, you can write reusable code with BaseEntity:
结合以上所有答案,您可以使用 BaseEntity 编写可重用的代码:
@Data
@NoArgsConstructor
@MappedSuperclass
public abstract class BaseEntity {
@Transient
public static final Sort SORT_BY_CREATED_AT_DESC =
Sort.by(Sort.Direction.DESC, "createdAt");
@Id
private Long id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@PrePersist
void prePersist() {
this.createdAt = LocalDateTime.now();
}
@PreUpdate
void preUpdate() {
this.updatedAt = LocalDateTime.now();
}
}
DAO object overloads findAll method - basically, still uses findAll()
DAO 对象重载 findAll 方法 - 基本上,仍然使用 findAll()
public interface StudentDAO extends CrudRepository<StudentEntity, Long> {
Iterable<StudentEntity> findAll(Sort sort);
}
StudentEntityextends BaseEntitywhich contains repeatable fields (maybe you want to sort by ID, as well)
StudentEntityextendsBaseEntity包含可重复的字段(也许您还想按 ID 排序)
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@Entity
class StudentEntity extends BaseEntity {
String firstName;
String surname;
}
Finally, the service and usage of SORT_BY_CREATED_AT_DESCwhich probably will be used not only in the StudentService.
最后,它的服务和用法SORT_BY_CREATED_AT_DESC可能不仅会在StudentService.
@Service
class StudentService {
@Autowired
StudentDAO studentDao;
Iterable<StudentEntity> findStudents() {
return this.studentDao.findAll(SORT_BY_CREATED_AT_DESC);
}
}

