Spring Data JPA @Query-选择最大

时间:2018-09-14 09:23:43

标签: spring-boot spring-data-jpa jpql

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

}

我遇到了另一个答案,但是它显式地使用了实体管理器,这并不相同

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!

发票类别(为简便起见,已简化):

@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;

...

更新:

  • 可能是findOne的变通方法,序列上具有DESC排序 专栏?

    @Query(“ SELECT i.sequence” +             “作为我的发票” +             “ WHERE i.fleetId =:fleetId” +             “按i.sequence DESC排序”)     长getMaxSequence(@Param(“ fleetId”)字符串FleetId);

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

更新2:

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

1 个答案:

答案 0 :(得分:0)

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

org.springframework.data.jpa.repository.Query

注释而不是

org.springframework.data.mongodb.repository.Query

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

发票findFirstByFleetIdOrderBySequenceDesc(String FleetId);

返回您需要的发票。