簡體   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