【发布时间】:2019-02-19 02:00:19
【问题描述】:
我正在尝试使用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 车队ID);
但我需要以某种方式将结果集限制为 1
更新 2:
修复了import org.springframework.data.jpa.repository.Query;仍然出错
【问题讨论】:
-
Spring Data 非常传统,以 find 开头的方法名称可能会被抛弃。将方法重命名为 'getMaxSequence' 会发生什么?
-
同理:org.springframework.data.mapping.PropertyReferenceException: No property getMaxSequence found for type Invoice!
-
你可以尝试使用 nativequery 并检查是否会出现同样的问题
-
您能否检查一下您是否正在使用 org.springframework.data.jpa.repository.Query 注释而不是任何其他注释?
-
@Query("select max(i.sequence) ...")没问题,也许您会遇到其他错误,但与此无关。 This unit test code(repository.getMaxCode) 可以证明。除此之外,注释@Repository不是必需的,应该删除。
标签: spring-boot spring-data-jpa jpql