JPA @Query问题与返回的对象有关

时间:2022-09-11 12:58:37

I have added this in my DAO:

我在我的DAO中添加了这个:

@Query("SELECT distinct LBL.cId, LBL from FooBar LBL ORDER BY LBL.collectedAt DESC")
    List<FooBar> findDistinctcIdOrderByCollectedAtDesc();

And then this is in my service

然后这是我的服务

List<FooBar> fooBars = this.liveBusLocationDao.findDistinctcIdOrderByCollectedAtDesc();

And this is what I got when I debug contents of fooBars

这是我在调试fooBars的内容时得到的

fooBars = {ArrayList@11035}  size = 1
 0 = {Object[2]@11093} 
   0 = "string"
   1 = {FooBar@11095} "FooBar(cId=string, internalcId=123456789012, createdAt=2011-11-02 02:59:12.208, collectedAt=2017-10-06 14:26:26.544)"

How can I traverse this result?

我怎样才能遍历这个结果?

2 个解决方案

#1


0  

You would need to create a result class and use special syntax in the jpa query if you want to use projection without getting the Object[] result.

如果要在不获取Object []结果的情况下使用投影,则需要创建结果类并在jpa查询中使用特殊语法。

package com.example

class ResultClass{

   int fieldOne;
   String fieldTwo;

  public (int fieldOne, intfieldTwo){
     // .. set fields
  }

}

and query:

@Query("SELECT distinct new com.example.ResultClass(LBL.cId, LBL.strProperty) from FooBar LBL ORDER BY LBL.collectedAt DESC")
    List<ResultClass> findDistinctcIdOrderByCollectedAtDesc();

#2


0  

Your Query is requesting on 2 attributes. you can make a Custom class that as the id and the object or you could just remove LBL.cId from SELECT

您的查询正在请求2个属性。你可以创建一个自定义类作为id和对象,或者你可以从SELECT中删除LBL.cId

Your request should be :

您的要求应该是:

@Query("SELECT distinct LBL from FooBar LBL ORDER BY LBL.collectedAt DESC")
List<FooBar> findDistinctcIdOrderByCollectedAtDesc();

The distinct is working on the whole Row. take a look to it, if you are not shure about it, you can use group by LBL

独特的是整个Row。看看它,如果你不是真的,你可以使用LBL组

https://*.com/a/10066187/3543153

#1


0  

You would need to create a result class and use special syntax in the jpa query if you want to use projection without getting the Object[] result.

如果要在不获取Object []结果的情况下使用投影,则需要创建结果类并在jpa查询中使用特殊语法。

package com.example

class ResultClass{

   int fieldOne;
   String fieldTwo;

  public (int fieldOne, intfieldTwo){
     // .. set fields
  }

}

and query:

@Query("SELECT distinct new com.example.ResultClass(LBL.cId, LBL.strProperty) from FooBar LBL ORDER BY LBL.collectedAt DESC")
    List<ResultClass> findDistinctcIdOrderByCollectedAtDesc();

#2


0  

Your Query is requesting on 2 attributes. you can make a Custom class that as the id and the object or you could just remove LBL.cId from SELECT

您的查询正在请求2个属性。你可以创建一个自定义类作为id和对象,或者你可以从SELECT中删除LBL.cId

Your request should be :

您的要求应该是:

@Query("SELECT distinct LBL from FooBar LBL ORDER BY LBL.collectedAt DESC")
List<FooBar> findDistinctcIdOrderByCollectedAtDesc();

The distinct is working on the whole Row. take a look to it, if you are not shure about it, you can use group by LBL

独特的是整个Row。看看它,如果你不是真的,你可以使用LBL组

https://*.com/a/10066187/3543153