英文:
How can I sort string values from DB in repository in functional Queries?
问题
如何在存储库层中使用函数查询对数据库中的字符串值进行排序?
除外可以使用的查询异常。
英文:
How can I sort a string values from DB in repository layer in functional Query?
Exception the query that can be utilized
答案1
得分: 1
以下是翻译好的部分:
可以在JPA查询中使用"order by"查询,例如,有一个名为"Student"的表(实体名称也是"Student"),其中包含学生的年龄和姓名。您需要按姓名对学生列表进行查询。
然后,您可以使用类似以下方式的JPA存储库方法:
List
或
List
英文:
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();
答案2
得分: 0
public List
String query = "SELECT name FROM my_table ORDER BY name ASC";
List
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;
}
英文:
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<String> and returned by the method. Note that you will need to handle any exceptions that may occur during the database access.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论