Search code examples
javasqlspringexceptionjpa

IllegalSelectQueryException and InvalidDataAccessApiUsageException


I use Query annotation for my project. While I call query, I get IllegalSelectQueryException. I want to update status column which is on Reservation table with WHERE the PNR number exists.

@Repository
public interface ReservationRepository extends JpaRepository<Reservation,String> {
    @Query("UPDATE Reservation SET Status =:Status WHERE pnr =:pnr")
    String setStatus( @Param("Status")String Status,@Param("pnr") String pnr);
}

Error

org.springframework.dao.InvalidDataAccessApiUsageException: Expecting a SELECT query : UPDATE Reservation SET Status = :Status WHERE pnr = :pnr at Caused by: org.hibernate.query.IllegalSelectQueryException: Expecting a SELECT Query [org.hibernate.query.sqm.tree.select.SqmSelectStatement], but found org.hibernate.query.sqm.tree.update.SqmUpdateStatement [UPDATE Reservation SET Status = :Status WHERE pnr = :pnr] at org.hibernate.query.sqm.internal.SqmUtil.verifyIsSelectStatement(SqmUtil.java:81) ~[hibernate-core-6.2.5.Final.jar:6.2.5.Final] at org.hibernate.query.sqm.internal.QuerySqmImpl.verifySelect(QuerySqmImpl.java:499) ~[hibernate-core-6.2.5.Final.jar:6.2.5.Final] ... 102 common frames omitted

I tried changing the query but nothing works


Solution

  • Add the @org.springframework.data.jpa.repository.Modifying annotation to the method and set the return value to void,because update queries can not return a value

    @Repository
    public interface ReservationRepository extends JpaRepository<Reservation,String> {
        @Modifying
        @Transactional
        @Query("UPDATE Reservation SET Status =:Status WHERE pnr =:pnr")
        void setStatus( @Param("Status")String Status,@Param("pnr") String pnr);
    }