休眠查询方法要求查询中返回所有列?

时间:2018-11-29 16:47:38

标签: java hibernate hibernate-native-query

我已经为存储库方法编写了本机查询,该存储库方法按特定列进行分组。

我无法按id分组,因为那样会破坏分组。

      @Query(nativeQuery = true, value = "SELECT description, model_year, take_rate, number " +
          "FROM foo f " +
          "INNER JOIN bar b " +
          "ON b.cycle_plan_code = b.cycle_plan_code " +
          "WHERE b.programme = :programme " +
          "AND b.build_event = :buildEvent " +
          "AND f.vehicle_line = :vehicleLine " +
          "GROUP BY description, take_rate, model_year, number")
  List<FooEntity> findAllFooByBar(@Param("vehicleLine") String vehicleLine, @Param("programme") String programme,
                                          @Param("buildEvent") String buildEvent);

我的实体中有一个@Id列,另一些列

@Table(name = "foos")
public class FooEntity {

  @Id
  private Long id;

  @Column(name = "cycle_plan_code")
  private String cyclePlanCode;

  @Column(name = "model_year")
  private String year;

  @Column(name = "vehicle_line", nullable = true)
  private String vehicleLine;

  @Column(name = "number")
  private Integer number;

  @Column(name = "description")
  private String description;

  @Column(name = "take_rate")
  private double takeRate;

}

访问存储库方法时,它将引发休眠状态

o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'id' not found.

我试图通过将其添加到选择子句中来对其进行破解

SELECT 0 as id

此过程正在进行,但是随后它抱怨查询未返回实体vehicle_linemodel_year的其他列 我必须将它们全部添加到查询中以使其工作。

我尝试在批注中使用nullable = true标志,但这不允许我从select子句中省略列。

如何返回仅包含我感兴趣的某些列的实体?

1 个答案:

答案 0 :(得分:1)

尝试使用投影: 用所需字段的获取器声明一个接口:

public interface SubFooEntity{
String getDescription();
String getModelYear();
Double getTakeRate();
Integers getNumber(); 
}

将存储库方法更改为以下:

 @Query("SELECT description, modelYear, takeRate, number " +
      "FROM foo f " +
      "INNER JOIN bar b " +
      "ON b.cyclePlanCode = b.cyclePlanCode " +
      "WHERE b.programme = :programme " +
      "AND b.build_event = :buildEvent " +
      "AND f.vehicle_line = :vehicleLine " +
      "GROUP BY description, takeRate, modelYear, number")


List<SubFooEntity> findAllFooByBar(@Param("vehicleLine") String vehicleLine, @Param("programme") String programme,
                                          @Param("buildEvent") String buildEvent);

此处有更多信息:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections