将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
# 1 楼答案
在实施之前有一些要点
findById()
的命名是-通过此Id查找内容,但您正在获取记录列表,因此命名不正确李>关于实施:
如果您希望提高查询效率,请执行以下操作: 您可以使用JPQL和hibernate
然后,您可以编写如下查询: