java - 将 JPQL 查询结果中的键集存储在 java 列表中
问题描述
我成功地执行了 jpql 查询并打印了存储在queryResults
变量中的结果。我接下来要实现的是仅将 ID(主键列)存储在没有日期(值)的列表中,但我不太确定这是否可能;也许使用类似 java 地图的东西。可能吗?如果是,如何轻松实现?
private static final TestDao Test_DAO = new TestDao();
@Test
public void testById() {
List<TestEntity> queryResults = TEST_DAO.findById(""); //The record from the sql query is stored in queryResults and findById("") is the method that executes the query in a TestDao class and it is called here
for (TestEntity qResult: queryResults) { // looping through the query result to print the rows
System.out.println(qResult.getId());
System.out.println(qResult.getDate());
}
System.out.println("This is the sql result " + queryResults );
}
Output:
This is the result [TestEntity(id=101, date=2020-01-19 15:12:32.447), TestEntity(id=102, date=2020-09-01 11:04:10.0)]// I want to get the IDs 101 and 102 and store in a list without the Dates
我尝试使用map
这种方式:
Map<Integer, Timestamp> map= (Map<Integer, Timestamp>) queryResults.get(0);
但我有一个例外:
java.lang.ClassCastException: TestEntity cannot be cast to java.util.Map
解决方案
实施前有几点。
- 你为什么将 DAO 定义为静态的?我认为这是一个糟糕的实现,除非我遗漏了您将其声明为静态的特定原因。您应该将其定义为成员变量而不是静态成员
- 该方法的命名 -
findById()
翻译成英文是 - find Something by this Id,但您正在获取记录列表,因此命名不正确。 - 如果ID属性不是表中的主键,则第 2 点无效,那么这是有道理的,但命名仍然不好。Id 是我们用来在数据库中定义主键的东西,应该并且将是唯一的。但是您的评论表明 ID 是唯一的,并且是主键。所以阅读数据库是如何工作的
- 而且即使不是唯一的,如果你通过一个Id来查找一些记录,为什么会在Records中得到不同的id!
关于实施:
- 更改现有代码:
private TestDao Test_DAO = new TestDao();
@Test
public void testById() {
List<TestEntity> queryResults = TEST_DAO.findById("");
List<Long> listOfIds = new ArrayList<>(); // Assuming Id is Long type, same logic for any type
for (TestEntity qResult: queryResults) {
System.out.println(qResult.getId());
listOfIds.add(qResult.getId()); // Just add it to the list
System.out.println(qResult.getDate());
}
}
如果您想提高查询效率:您可以使用JPQL和hibernate
然后,您可以编写如下查询:
String query = "select te.id from TestEntity te";
// Create the TypedQuery using EntityManager and then get ResultSet back
List<Long> ids = query.getResultList();
- 在使用 Spring-Data-Jpa 的情况下,您可以定义存储库并定义方法并使用 @Query 注释传递查询。春季数据 JPA
推荐阅读
- alias - Doxygen: xrefitem key works with '\' but not with '@' in the documentation
- excel - Writing from an Excel row onto a Word docx
- python - Django Queryset Annotate value with latest related object
- python - Print a list in HTML file using Django
- windows - I need to know, how can I add many URLs to the windows hosts file?
- css - CSS Grid wrapping with grid-area coordinates
- wix - 从 Wix 中的自定义表中读取值
- nginx - 重定向时如何在nginx中删除端口号
- python - 如何使用python和curses滚动终端中显示的文件内容
- r - 使用 R 中的 dbplyr 计算 SQL 表的每行的 TRUE/FALSE 值