有 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

共 (1) 个答案

  1. # 1 楼答案

    在实施之前有一些要点

    1. 为什么要将DAO定义为静态的?我认为这是一个糟糕的实现,除非我遗漏了一个特定的原因,您将其声明为静态。您应该将其定义为成员变量,而不是静态成员
    2. 翻译成英语的方法-findById()的命名是-通过此Id查找内容,但您正在获取记录列表,因此命名不正确
    3. 如果ID属性不是表中的主键,则第2点无效,这样做是有意义的,但命名仍然不好。Id是我们用来在数据库中定义主键的东西,它应该是唯一的,也将是唯一的。但您的评论表明ID是唯一的,并且是主键。因此,请阅读数据库的工作原理
    4. 即使不是唯一的,如果你通过一个Id找到一些记录,为什么会在记录中得到不同的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. 在使用SpringDataJPA的情况下,您可以定义存储库和方法,并使用@query注释传递查询Spring Data JPA