Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 414 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use OrderBy with findAll in Spring Data

#1
I am using spring data and my DAO looks like

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?
Reply

#2
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 [`Sort`](

[To see links please register here]

) class. The repository has a [`findAll(Sort)`](

[To see links please register here]

) method that you can pass an instance of `Sort` to. For example:

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");
}
}
Reply

#3
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.

**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"
^
Reply

#4
Yes you can sort using query method in Spring Data.

Ex:ascending order or descending order by using the value of the id field.

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][1]


[1]:

[To see links please register here]

Reply

#5
Please have a look at the [Spring Data JPA - Reference Documentation, section 5.3. Query Methods][1], especially at section [5.3.2. Query Creation][2], in "*Table 3. Supported keywords inside method names*" (links as of 2019-05-03).

I think it has exactly what you need and same query as you stated should work...


[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#6
Simple way:

repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));

Source:

[To see links please register here]

Reply

#7
Combining all answers above, you can write reusable code with 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()`
```
public interface StudentDAO extends CrudRepository<StudentEntity, Long> {

Iterable<StudentEntity> findAll(Sort sort);

}
```


`StudentEntity` extends `BaseEntity` which contains repeatable fields (maybe you want to sort by ID, as well)
```
@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_DESC` which probably will be used not only in the `StudentService`.

```
@Service
class StudentService {

@Autowired
StudentDAO studentDao;

Iterable<StudentEntity> findStudents() {
return this.studentDao.findAll(SORT_BY_CREATED_AT_DESC);
}
}
```
Reply

#8
Sort sortBy = Sort.by(new Sort.Order(Sort.Direction.ASC, "name").ignoreCase());

repository.findAll(sortBy);
Reply

#9
I try in this example to show you a complete example to personalize your OrderBy sorts

import java.util.List;
import org.springframework.data.domain.Page;

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 :




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);
}
}

Reply

#10
for spring boot 3, your Repository should implement JpaRepository and define the sort as follow :

```
Sort sortBy = Sort.by(Sort.Direction.DESC, "id");
```
then use it :
```
repository.findAll(sortBy);
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through