Search code examples
javaspringspring-bootspring-data-jpaspring-data

How to invoke custom query in Spring Boot JPA Repository


I am trying to invoke a custom query through a custom method in Spring Boot Data JPA.

    @Repository
    public interface FlightRepository extends JpaRepository<Flight, Integer> {
    
    
        @Query("select * from flight")
        void executeMyQuery();
    }

But when try to run the application, I am getting below error

No property 'executeMyQuery' found for type 'Flight'

I am using Spring Boot Version 3.1.1 (tried with 2.7.13 as well but no luck)

Thanks in advance.


Solution

  • You need to use JPQL inside @Query annotation for custom query and also you can use return type to get the results.

    @Query("SELECT f FROM Flight f")
    List<Flight> fetchFlights();
    

    Here is more details https://www.baeldung.com/spring-data-jpa-query

    Or you can use native SQL for query using nativeQuery = true

    @Query("SELECT * FROM Flight", nativeQuery = true)
    List<Flight> fetchFlights();
    

    BTW you can also use existing findAll() method also to fetch all data.

    flightRepository.findAll();