选择最大本机查询休眠

时间:2018-09-19 15:53:12

标签: mysql hibernate jpa

我正在尝试使用带有@Query批注

的本机查询来获取表中列的最大值

我试图从此处的示例中得出:https://www.baeldung.com/spring-data-jpa-query

 @Query(value = "SELECT max(i.sequence) " +
            "FROM invoices as i " +
            "WHERE i.fleet_id = ?1", nativeQuery = true)
    Long findMaxSequence(String fleetId);

我也尝试过:

@Query(value = "SELECT max(i.sequence) " +
        "FROM invoices as i " +
        "WHERE i.fleet_id = :fleetId", nativeQuery = true)
Long findMaxSequence(@Param("fleetId") String fleetId);

当我以以下方式调用方法时:

long maxSeq = invoiceRepository.findMaxSequenceForFleetId(invoice.getFleetId());

我得到一个NullPointerException。有什么想法吗?

Invoice实体看起来像这样:

@Entity
@Table(name = "invoices"}
public class Invoice implements Serializable {


    @Id
    private String id;

    @Column
    private long sequence;

    @Column(length = 12)
    private String fleetId;

    // ...
}

1 个答案:

答案 0 :(得分:0)

问题是由于数据库为空,因此查询返回null

和诸如long之类的基本类型不能分配给空值。奇怪的是编译器没有抱怨。.

我修改了我的代码,如下所示:

Long maxSeq = invoiceRepository.findMaxSequenceForFleetId(invoice.getFleetId());
if(maxSeq == null){
    maxSeq = 0L;
}