Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA @Query - select max

I m trying to write a query using select max&where with @Query

The following won't work, how can I fix it?

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);

}

I've run into another answer but it is using the entity manager explicitly, os its not the same

How do I write a MAX query with a where clause in JPA 2.0?

the error is :

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!

the invoice class (simplified for brevity):

@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;

...

Update:

  • maybe a work-around with findOne with DESC sort on the sequence column?

    @Query("SELECT i.sequence " + "FROM Invoice as i " + "WHERE i.fleetId = :fleetId " + "ORDER BY i.sequence DESC ") Long getMaxSequence(@Param("fleetId") String fleetId);

But i need to LIMIT the resultset to 1 somehow

Update 2:

fixed the import org.springframework.data.jpa.repository.Query; still in error

like image 552
Orkun Ozen Avatar asked Sep 12 '25 17:09

Orkun Ozen


1 Answers

Since you're using JPA repositories, use:

org.springframework.data.jpa.repository.Query

annotation instead of

org.springframework.data.mongodb.repository.Query

You can create a query method, without using @Query annotation, like:

Invoice findFirstByFleetIdOrderBySequenceDesc(String fleetId);

that return the invoice that you need.

like image 170
eltabo Avatar answered Sep 15 '25 11:09

eltabo