将JPQL查询结果中的键集存储在Java列表中

huangapple go评论78阅读模式
英文:

Storing the keysets from a JPQL query result in a java list

问题

成功执行了jpql查询并打印了存储在queryResults变量中的结果。我想接下来要实现的是,将只有ID(主键列)存储在一个列表中,而不包括日期(值),但我不太确定这是否可能;或许可以使用类似于java map的东西。这种做法可行吗?如果可以,如何轻松实现?

private static final TestDao Test_DAO = new TestDao();

@Test
public void testById() {
    List<TestEntity> queryResults = TEST_DAO.findById(""); // 从sql查询中获取的记录存储在queryResults中,findById("")是在TestDao类中执行查询的方法,在这里被调用
    
    List<Integer> idsOnly = new ArrayList<>();
    for (TestEntity qResult : queryResults) { // 循环遍历查询结果以打印行
        idsOnly.add(qResult.getId()); // 仅将ID添加到列表中
    }
    
    System.out.println("This is the sql result " + idsOnly);
}

输出:

This is the result [101, 102] // 我想要获取ID 101 和 102,并将其存储在一个列表中,不包括日期

我尝试过使用以下方式来使用map

Map<Integer, Timestamp> map = (Map<Integer, Timestamp>) queryResults.get(0);

但是我遇到了一个异常:

java.lang.ClassCastException: TestEntity cannot be cast to java.util.Map
英文:

I was successfully able to execute a jpql query and print the result which is stored in a queryResults variable. What I want to achieve next is storing just the IDs (primary key column) in a list without the date (value), but I am not too sure if this is possible; perhaps using something like a java map. Is it possible? If yes, how can this be easily achieved?

  private static final TestDao Test_DAO = new TestDao();

 @Test
 public void testById() {
List&lt;TestEntity&gt; queryResults = TEST_DAO.findById(&quot;&quot;); //The record from the sql query is stored in queryResults and findById(&quot;&quot;) 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(&quot;This is the sql result &quot; + 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

I tried using a map this way:

Map&lt;Integer, Timestamp&gt; map= (Map&lt;Integer, Timestamp&gt;) queryResults.get(0); but I got an exception:

java.lang.ClassCastException: TestEntity cannot be cast to java.util.Map

答案1

得分: 1

在实施之前有一些要点。

  1. 为什么将DAO定义为静态?除非我漏掉了你声明它为静态的特定原因,否则我认为这是一个不好的实现。你应该将其定义为成员变量,而不是静态成员。
  2. 方法的命名 - findById() 的英文翻译是 - 根据ID查找某个东西,但你正在获取记录列表,所以命名不正确。
  3. 如果ID属性不是表中的主键,则第2点无效,这时就有意义了,但命名仍然不好。在数据库中,ID是我们用来定义主键的,应该是唯一的。但你的注释表明ID是唯一的和主键。因此,了解一下数据库如何工作
  4. 即使不唯一,如果将ID传递给查找一些记录,为什么在记录中会得到不同的ID !!!

关于实现:

  1. 对你现有的代码进行更改:
private TestDao testDAO = new TestDao();

@Test
public void testById() {
  List<TestEntity> queryResults = testDAO.findById("");
  List<Long> listOfIds = new ArrayList<>(); // 假设ID是Long类型,对于任何类型都适用相同的逻辑
  for (TestEntity qResult : queryResults) {
    System.out.println(qResult.getId());
    listOfIds.add(qResult.getId());   // 只是将其添加到列表中
    System.out.println(qResult.getDate());
  }
}

如果你想以查询方式更高效:
你可以使用JPQLhibernate

然后你可以编写查询:

String query = "select te.id from TestEntity te";
// 使用EntityManager创建TypedQuery,然后获取结果集
List<Long> ids = query.getResultList();
  1. 如果使用Spring Data Jpa,你可以定义仓库并使用@Query注解传递查询。Spring Data JPA
英文:

There are some points before the implementation.

  1. Why are you defining DAO as static? I think this is a bad implementation unless I am missing a particular reason you declared it static. You should define this as a member variable and not a static member
  2. The naming of the method - findById() translated in English is - find Something by this Id, but you are fetching a list of Records, so naming is not correct.
  3. Point 2 becomes invalid if ID property is not a Primary Key in your table, then it makes sense, but still naming is bad. Id is something we use to define Primary Key in the Database and should be and will be unique. But your comments suggest that ID is unique and the Primary Key. So read about how Databases work
  4. And even if not unique, if you pass an Id to find some records, why will get different ids in the Records !!!

About implementation:

  1. Changing in your existing code:
private TestDao Test_DAO = new TestDao();

@Test
public void testById() {
  List&lt;TestEntity&gt; queryResults = TEST_DAO.findById(&quot;&quot;);
  List&lt;Long&gt; listOfIds = new ArrayList&lt;&gt;(); // 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());
  }
       
}

In case you want to be efficient with the query:
You can use JPQL and hibernate

You can then write a query like:

String query = &quot;select te.id from TestEntity te&quot;;
// Create the TypedQuery using EntityManager and then get ResultSet back
List&lt;Long&gt; ids = query.getResultList();
  1. In case of using Spring-Data-Jpa, you can define the repository and define the method and pass the query with @Query annotation. Spring Data JPA

huangapple
  • 本文由 发表于 2020年8月15日 06:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63420919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定