【发布时间】:2020-08-16 06:45:00
【问题描述】:
我成功地执行了 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 但它显然返回一个列表。键在表中应该是唯一的。它接受一个空字符串作为参数!当然你得到一个例外。 queryResults.get(0) 返回一个 TestEntity 对象,您要求 Java 将其转换为 Map !
-
我是根据最后一行的评论来回答的。其实我不是在回答,我是在帮你自己回答。您这样做是为了获取 id 并打印它: System.out.println(qResult.getId());所以你已经有了 id,每次迭代你都有一个 id。你不能把它添加到列表中吗???
-
queryResults 已经是键和值的列表,但我想要一个仅包含键的列表。请证明您认为它是如何实现的。如何仅将 ID 添加到列表中?谢谢
-
queryResults 已经是键和值的列表 - 这是不正确的。 queryResults 是一个 TestEntity 列表
-
List
queryResults = TEST_DAO.findById("") 您正在获取一个 TestEntity 列表。然后你遍历列表以提取 Id 和 Date 并打印它。如果你能做到这一点,你能不将这些 id 添加到列表中并获取 Id 列表吗?