pass parameters to @query in JPA

There are two ways to pass parameters to @query in JPA.

First way, using indexed Parameters

@Repository
public interface CarRepository extends JpaRepository<CarDto, String> {

     //Here we use the position in the parameters (careful! start with 1)
     @Modifying
     @Query("update CarDto c set c.color = ?1 , c.brand = ?2 where c.numberOfDoors = 5")
     void updateColorAndBrand(String color, String brand);

}

Second way, using named Parameters

@Repository
public interface CarRepository extends JpaRepository<CarDto, String> {

     //Here we update use @Param
     @Modifying
     @Query("update CarDto c set c.color = :color, c.brand = :brand where c.numberOfDoors = 5")
     void updateColorAndBrand(@Param("color") String color, @Param("brand") String brand);

}

Source: documentation

For more interesting tutorials & guides just check themĀ HERE.

Leave a Reply

Your email address will not be published. Required fields are marked *