Java 如何使用 Hibernate 和 Spring-boot 从 JPA 查询返回 SUM?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51637103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:11:37  来源:igfitidea点击:

How do I Return SUM from JPA Query Using Hibernate and Spring-boot?

javaspringjpajpql

提问by Benjamin Gowers

I am trying to use JPA and JPQL to query my entity and return the sum of a column (total days) from the table. I thought I had set it up right but I am getting this error:

我正在尝试使用 JPA 和 JPQL 来查询我的实体并从表中返回一列的总和(总天数)。我以为我已经设置好了,但我收到了这个错误:

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myRepository':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Validation failed for query for method
public abstract java.lang.Float
com.nissan.rca.repository.MyRepository.selectTotals()!

Here is a representation of my entity:

这是我的实体的表示:

@Entity
@Table(name = "TABLENAME")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private MyEntityCompositeKey myEntityCompositeKey;

    @Column(name = "raiser_id")
    private String raiserID;

    @Column(name = "total_days")
    private Float totalDays;

and here is my repository in which I make the query assigned to a method:

这是我的存储库,我在其中将查询分配给方法:

@Repository
public interface MyRepository extends JpaRepository<MyEntity, ID> {
    @Query("SELECT SUM(total_days) FROM MyEntity")
    Float selectTotals();
}

I call the selectTotals() method from myRepository object in my rest controller for the api mapping.

我从我的 rest 控制器中的 myRepository 对象调用 selectTotals() 方法以进行 api 映射。

@GetMapping("/getForecastTotals")
public Float getForecastTotals() {
    return myRepository.selectTotals();
}

I'm unsure as to why it can't be returned as a float.

我不确定为什么它不能作为浮点数返回。

采纳答案by sedooe

It's not a valid JPQL.

它不是有效的 JPQL。

You either should have:

你应该有:

@Query("SELECT SUM(m.totalDays) FROM MyEntity m")

@Query("SELECT SUM(m.totalDays) FROM MyEntity m")

or, make it a native one:

或者,使其成为原生的:

@Query(value = "SELECT SUM(total_days) FROM MyEntity", nativeQuery = true)

@Query(value = "SELECT SUM(total_days) FROM MyEntity", nativeQuery = true)

回答by Yogendra Mishra

change your JPQL to @Query("SELECT SUM(m.totalDays) FROM MyEntity m")

将您的 JPQL 更改为 @Query("SELECT SUM(m.totalDays) FROM MyEntity m")