我正在尝试使用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()!
这是我的实体的代表:
@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;
这是我的存储库,在其中我将查询分配给一个方法:
@Repository
public interface MyRepository extends JpaRepository<MyEntity, ID> {
@Query("SELECT SUM(total_days) FROM MyEntity")
Float selectTotals();
}
我从rest控制器的myRepository对象中调用selectTotals()方法进行api映射。
@GetMapping("/getForecastTotals")
public Float getForecastTotals() {
return myRepository.selectTotals();
}
我不确定为什么不能将其作为浮点数返回。
答案 0 :(得分:1)
这不是有效的JPQL。
您应该有:
@Query("SELECT SUM(m.totalDays) FROM MyEntity m")
或者将其设为本机:
@Query(value = "SELECT SUM(total_days) FROM MyEntity", nativeQuery = true)
答案 1 :(得分:0)
将JPQL更改为@Query("SELECT SUM(m.totalDays) FROM MyEntity m")
答案 2 :(得分:0)
你可以通过映射一个新的 POJO 来做到这一点
@Repository
public interface MyRepository extends JpaRepository<MyEntity, ID> {
@Query("SELECT new com.NewPojo(SUM(m.totalDays)) FROM MyEntity m")
NewPojo selectTotals();
}
class NewPojo {
Float days;
public NewPojo(Float days) {
this.days = days;
}
}