繁体   English   中英

如何在Spring JPA中使用@Query?

[英]How to use @Query in Spring JPA?

我正在尝试使用 @Query 注释通过 spring(2.7.6) jpa 访问类型为收入的费用。 数据库截图 postgresql

终端错误:

 Error creating bean with name 'expenseController': Unsatisfied dependency expressed through field 'expenseService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'expenseService': Unsatisfied dependency expressed through field 'expenseRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'expenseRepository' defined in com.ivy.expensely.repository.ExpenseRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.ivy.expensely.repository.ExpenseRepository.findByType(java.lang.String); Reason: Validation failed for query for method public abstract java.util.Optional com.ivy.expensely.repository.ExpenseRepository.findByType(java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.Optional com.ivy.expensely.repository.ExpenseRepository.findByType(java.lang.String)!

我正在尝试在 ExpenseRepository 中执行;

import com.ivy.expensely.model.Expense;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface ExpenseRepository extends JpaRepository<Expense,Long> {

//    @Query(value = "select sum(amount) from expense where type:income",nativeQuery = true)
@Query("SELECT sum(amount) FROM expense WHERE type='income'")
    public Optional<Expense> findByType(String param_name);
}

Model 看起来像这样:

@NoArgsConstructor
@AllArgsConstructor
@Entity
@Data
@Table(name="expense")
public class Expense {

    @Id
    private Long id;

    private Instant expensedate;

    private String description;

    private String location;

    private Long amount;

    private String type;

    @ManyToOne
    private Category category;

    @JsonIgnore
    @ManyToOne
    private User user;

请帮我弄清楚如何执行此操作

Sum 返回 Long(因为它是金额的总和,是 Long),所以试试这个:

@Query("SELECT sum(e.amount) FROM expense e WHERE e.type='income'")
public Long findByType(String param_name);

在 JPQL 查询中,您必须指定 where 子句字段的表。 还要记住为存储库方法设置正确的返回类型。 更多信息,请访问baeldung 相关问题在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM