boot从JPA查询返回SUM

boot从JPA查询返回SUM

本文介绍了如何使用Hibernate和Spring-boot从JPA查询返回SUM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JPA和JPQL查询我的实体,并从表中返回一列的总和(总天数).我以为我设置正确,但是却收到此错误:

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:

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()!

这是我的实体的代表:

@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();
}

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

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

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

我不确定为什么不能将其作为浮点数返回.

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

推荐答案

这不是有效的JPQL.

It's not a valid JPQL.

您应该有:

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

或者将其设为本机:

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

这篇关于如何使用Hibernate和Spring-boot从JPA查询返回SUM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:41