gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:32:17 26 4
gpt4 key购买 nike

我已经为按特定列分组的存储库方法编写了 native 查询。

我无法按 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;

}

访问存储库方法时会引发 hibernate

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

我试图通过将其添加到 select 子句来破解它

选择 0 作为 ID

此过程继续进行,但随后它提示查询没有返回实体 vehicle_linemodel_year 的其他列我必须将它们全部添加到查询中才能使其正常工作。

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

如何返回仅返回我感兴趣的部分列的实体?

最佳答案

尝试使用投影:声明一个带有所需字段的 getter 的接口(interface):

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

关于java - Hibernate查询方法需要在查询中返回所有列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com