我正在尝试使用
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);
}
我遇到了另一个答案,但它明确使用实体管理器,所以不同。
错误是:
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方法,按照序列列进行降序排序来解决问题?
@Query("SELECT i.sequence " + "FROM Invoice as i " + "WHERE i.fleetId = :fleetId " + "ORDER BY i.sequence DESC ") Long getMaxSequence(@Param("fleetId") String fleetId);
但是我需要对结果集进行限制,只返回一个结果。
更新2:
已经修复了import org.springframework.data.jpa.repository.Query;
,但还存在错误。
@Query("select max(i.sequence) ...")
是正确的,也许你会遇到其他错误,但不是关于这个的。这个单元测试代码(repository.getMaxCode)可以证明它。除此之外,@Repository
注解是不必要的,应该被移除。 - RJ.Hwang