首页 > 解决方案 > Spring Data JPA @Query - 选择最大值

问题描述

我正在尝试使用select max& wherewith编写查询@Query

以下不起作用,我该如何解决?

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
interface IntermediateInvoiceRepository extends JpaRepository<Invoice, String> {

@Query("SELECT max(i.sequence) " +
        "FROM Invoice as i " +
        "WHERE i.fleetId = :fleetId" +
        "   AND i.sequence IS NOT NULL")
Long findMaxSequence(@Param("fleetId") String fleetId);

}

我遇到了另一个答案,但它明确使用实体管理器,操作系统不一样

如何在 JPA 2.0 中使用 where 子句编写 MAX 查询?

错误是:

2018-09-14T09:27:57,180Z  [main] ERROR o.s.boot.SpringApplication     - Application startup failed
org.springframework.data.mapping.PropertyReferenceException: No property findMaxSequence found for type Invoice!

发票类(为简洁起见):

@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "invoices", indexes = {
        @Index(name = "IDX_FLEET", columnList = "fleetId", unique = false)
        ,
        @Index(name = "IDX_USERSSS", columnList = "userId", unique = false)
        ,
        @Index(name = "IDX_TIME", columnList = "invoiceDate", unique = false)
        ,
        @Index(name = "IDX_SEQUENCE", columnList = "sequence", unique = false)
})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Invoice implements Serializable {

    private static final long serialVersionUID = 1L;

    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "CHAR(36)")
    @Id
    private String id;

    @Column
    private long sequence;

...

更新:

但我需要以某种方式将结果集限制为 1

更新 2:

修复了import org.springframework.data.jpa.repository.Query;仍然错误

标签: spring-bootspring-data-jpajpql

解决方案


由于您使用的是 JPA 存储库,因此请使用:

org.springframework.data.jpa.repository.Query

注释而不是

org.springframework.data.mongodb.repository.Query

您可以创建查询方法,而无需使用 @Query 注释,例如:

发票 findFirstByFleetIdOrderBySequenceDesc(StringfleetId);

返回您需要的发票。


推荐阅读