Spring 数据 JPA @Query - select 最大值

Spring Data JPA @Query - select max

我正在尝试使用 select max&where@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);

}

我已经 运行 进入另一个答案,但它明确地使用了实体管理器,os 它不一样

How do I write a MAX query with a where clause in JPA 2.0?

错误是:

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!

发票class(为简洁起见进行了简化):

@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

更新二:

修复了 import org.springframework.data.jpa.repository.Query; 仍然出错的问题

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

org.springframework.data.jpa.repository.Query

注释而不是

org.springframework.data.mongodb.repository.Query

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

发票 findFirstByFleetIdOrderBySequenceDesc(String fleetId);

return 您需要的发票。

我找到了解决方法:

创建一个返回 Page 并接受 Pageable 的简单存储库方法:

Page<Invoice> findByFleetId(String fleetId, Pageable pageable);

这样我们可以通过以下方式模仿 ORDER BY sequence LIMIT 1

long maxNewSeq = 0;
PageRequest pageRequest = new PageRequest(0, 1, Sort.Direction.DESC, "sequence");
Page<Invoice> pageableInvoices = invoiceRepository.findByFleetId(invoice.getFleetId(), pageRequest);
if(pageableInvoices.getTotalElements() > 0){
    maxNewSeq = pageableInvoices.getContent().get(0).getSequence();
}

invoice.setSequence(Math.max(0, maxNewSeq) + 1);

看起来很有魅力。