Search code examples
javaspring-bootjpaspring-data-jparepository

How to pass path variable to JPA repository from controller


How to pass a path variable to JPA repository from controller.

I have a controller here and from the front End I am getting a variable.

Here is my controller :

@GetMapping("/getTransictionsAndInstruments/{id}")
    public List<TransictionProjection> getTransitionInstrument(@PathVariable Long id){
        return transictionrepository.getTransictionsAndInstruments();
    }

Based on this id I want some alteration in my result. I have already a query and want to use this id in the repository. So how can I pass that in the repository.

@Repository
public interface TransictionRepository extends JpaRepository<Transictions, Long>{
    
    @Query(value = "SELECT transiction.user_id, transiction.quantity, transiction.instrument_name, transiction.Price, instrument.LTP, instrument.jo_caps FROM instrument INNER JOIN transiction ON instrument.instrument = transiction.instrument_name where transiction.User= id", nativeQuery = true)
    
    
    List<TransictionProjection> getTransictionsAndInstruments();
}

I want to include this line in my query where transiction.User= id

Any help how to achieve this.


Solution

  • I think this can be achieved by following: Adding :id in your native query and passing id in function.

    @Query(value = "SELECT transiction.user_id, transiction.quantity, transiction.instrument_name, 
    transiction.Price, instrument.LTP, instrument.jo_caps FROM instrument INNER JOIN transiction ON instrument.instrument = transiction.instrument_name 
    where transiction.User= :id", nativeQuery = true)
    List<TransictionProjection> getTransictionsAndInstruments(Long id);