Hibernate 查询方法需要在查询中返回所有列吗?

Hibernate query method requires all columns being returned in 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 子句来破解它

SELECT 0 as id

这会继续进行,但是它会抱怨查询没有 return 实体的其他列 vehicle_linemodel_year 我必须将它们全部添加到查询中才能使其正常工作。

我尝试了注释中的 nullable = true 标志,但这不允许我从 select 子句中省略列。

我如何 return 只包含我感兴趣的某些列的实体 return?

尝试使用投影: 用你想要的字段的getter声明一个接口:

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