0

How can I sort a string values from DB in repository layer in functional Query?

Exception the query that can be utilized

2 Answers2

1

You can use order by queries in JPA queries, as an example, there is a table called Student (entity name also Student) with their age and name. You need to query the student list ordered by name.

then you can use a JPA repository method like this

List<Student> findByOrderByNameDesc();

or

List<Student> findByOrderByNameAsc();
Hashila
  • 56
  • 9
0
public List<String> getSortedNames() {
String query = "SELECT name FROM my_table ORDER BY name ASC";
List<String> names = new ArrayList<>();

try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database", "username", "password");
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(query)) {

    while (rs.next()) {
        String name = rs.getString("name");
        names.add(name);
    }
} catch (SQLException ex) {
    ex.printStackTrace();
}

return names;

}

This method retrieves the name column values from the my_table table in ascending order using the ASC keyword in the ORDER BY clause. The retrieved names are stored in a List and returned by the method. Note that you will need to handle any exceptions that may occur during the database access.

JoFyNi
  • 1
  • 2