Orkun
Orkun

Reputation: 7248

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:

But i need to LIMIT the resultset to 1 somehow

Update 2:

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

Upvotes: 3

Views: 17735

Answers (2)

eltabo
eltabo

Reputation: 3807

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.

Upvotes: 5

Orkun
Orkun

Reputation: 7248

I ve found a workaround :

create a simple repository method returning Page and accepting a Pageable:

Page<Invoice> findByFleetId(String fleetId, Pageable pageable);

This way we can imitate an ORDER BY sequence LIMIT 1 via the following:

long maxNewSeq = 0;
PageRequest pageRequest = new PageRequest(0, 1, Sort.Direction.DESC, "sequence");
Page<Invoice> pageableInvoices = invoiceRepository.findByFleetId(invoice.getFleetId(), pageRequest);
if(pageableInvoices.getTotalElements() > 0){
    maxNewSeq = pageableInvoices.getContent().get(0).getSequence();
}

invoice.setSequence(Math.max(0, maxNewSeq) + 1);

seems to work like a charm.

Upvotes: 0

Related Questions