首页 > 解决方案 > 将 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

标签: javajpql

解决方案


实施前有几点。

  1. 你为什么将 DAO 定义为静态的?我认为这是一个糟糕的实现,除非我遗漏了您将其声明为静态的特定原因。您应该将其定义为成员变量而不是静态成员
  2. 该方法的命名 -findById()翻译成英文是 - find Something by this Id,但您正在获取记录列表,因此命名不正确。
  3. 如果ID属性不是表中的主键,则第 2 点无效,那么这是有道理的,但命名仍然不好。Id 是我们用来在数据库中定义主键的东西,应该并且将是唯一的。但是您的评论表明 ID 是唯一的,并且是主键。所以阅读数据库是如何工作的
  4. 而且即使不是唯一的,如果你通过一个Id来查找一些记录,为什么会在Records中得到不同的id!

关于实施:

  1. 更改现有代码:
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());
  }
       
}

如果您想提高查询效率:您可以使用JPQLhibernate

然后,您可以编写如下查询:

String query = "select te.id from TestEntity te";
// Create the TypedQuery using EntityManager and then get ResultSet back
List<Long> ids = query.getResultList();
  1. 在使用 Spring-Data-Jpa 的情况下,您可以定义存储库并定义方法并使用 @Query 注释传递查询。春季数据 JPA

推荐阅读