spring-boot - Spring Data JPA @Query - 选择最大值
问题描述
我正在尝试使用select max
& where
with编写查询@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;
...
更新:
也许是 findOne 在序列列上使用 DESC 排序的解决方法?
@Query("SELECT i.sequence " + "FROM Invoice as i " + "WHERE i.fleetId = :fleetId " + "ORDER BY i.sequence DESC ") Long getMaxSequence(@Param("fleetId") StringfleetId);
但我需要以某种方式将结果集限制为 1
更新 2:
修复了import org.springframework.data.jpa.repository.Query;
仍然错误
解决方案
由于您使用的是 JPA 存储库,因此请使用:
org.springframework.data.jpa.repository.Query
注释而不是
org.springframework.data.mongodb.repository.Query
您可以创建查询方法,而无需使用 @Query 注释,例如:
发票 findFirstByFleetIdOrderBySequenceDesc(StringfleetId);
返回您需要的发票。
推荐阅读
- java - 在 Java8 中使用流重写
- c - perf_event 报告意外的缓存未命中量:访问数组中的 N 个元素会导致 2N 次缓存未命中
- python - 尝试从列表中删除重复时位于位置打印语句的 Python 生成器对象
- r - 用数字替换文本值
- gcloud - GCloud 构建 YAML 替换不起作用
- ios - 如何在我们应用快照时停止 UICollectionViewDiffableDataSource 滚动集合视图?
- reactjs - 我有样式组件,想迁移到 scss,
- java - 特殊字符未写入 csv 文件
- python-3.x - 正则表达式 - 如果外括号前面有特定字符,则不匹配任何内括号
- javascript - 在 ReactJs 中将所选选项从一个选择添加到另一个选择