【问题标题】:Using distinct in Spring data over multiple columns在多列的 Spring 数据中使用 distinct
【发布时间】:2013-05-30 17:42:23
【问题描述】:

我的领域模型是这样的:

CollectedData {
  String name;
  String description;
  int count;
  int xAxis,
  int yAxis
}

使用 Spring 数据存储库查询,我想检索所有唯一的行(唯一的名称、xAxis、yAxis)

我正在尝试这样的事情

@Query("select distinct a.name, a.xAxis, a.yAxis from CollectedData a")
List<CollectedData> findAllDistinctData();

所以,当我这样做时

List<CollectedData> records= findAllDistinctData();
for (CollectedData record : records) { //Exception on this line
 }

例外 [Ljava.lang.Object;无法转换为 CollectedData。

有没有其他方法可以为此编写查询?

【问题讨论】:

    标签: spring hibernate spring-data spring-data-jpa


    【解决方案1】:

    您可以使用 JPA 的构造函数表达式功能来返回一个仅包含您感兴趣的列的更具体的对象,而不是返回一个对象。另请参阅以下答案:

    JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped

    根据您的示例,您可以创建一个仅包含您感兴趣的列的新对象:

    SELECT DISTINCT new com.mypackage.MyInterestingCollectedData(a.name, a.xAxis, a.yAxis) from CollectedData a
    

    【讨论】:

      【解决方案2】:

      @Query 返回ArrayList of Object(s) 而不是特定类型的对象。所以你必须定义一些像

      @Query("select distinct a.name, a.xAxis, a.yAxis from CollectedData a")
      List<Object> findAllDistinctData();
      

      然后根据您的要求进行投射,

      List<Object> cdataList=findAllDistinctData();
      for (Object cdata:cdataList) {
         Object[] obj= (Object[]) cdata;
           String name = (String)obj[0];
          String description = (String)obj[1];;
       ...
        }
      

      【讨论】:

      • 补充和重要的说明。只需使用一个非常简单的 REST 控制器,并在对多个列使用 distinct 时避免使用 Spring Data。
      • 就我而言,我需要将@Query 返回的List&lt;Object&gt; 转换为List&lt;MyInterface&gt;,其中MyInterface 是一个java 接口。我不能使用任何其他方式,但这有效。谢谢
      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 2012-08-09
      • 1970-01-01
      • 2021-05-29
      • 2022-01-02
      相关资源
      最近更新 更多