我正在尝试使用 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);
}
我遇到了另一个答案,但它明确地使用了实体管理器,操作系统不一样
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 "+ “作为我的发票” + “哪里 i.fleetId = :fleetId” + “按 i.sequence DESC 排序”) Long getMaxSequence(@Param("fleetId") String fleetId);
但我需要以某种方式将结果集限制为 1
更新 2:
修复了 import org.springframework.data.jpa.repository.Query;
仍然出错
最佳答案
由于您使用的是 JPA 存储库,因此请使用:
org.springframework.data.jpa.repository.Query
注解代替
org.springframework.data.mongodb.repository.Query
您可以创建一个查询方法,而不使用@Query 注释,例如:
发票 findFirstByFleetIdOrderBySequenceDesc(String fleetId);
返回您需要的发票。
关于spring-boot - Spring Data JPA @Query - 选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52328865/