1

I've been trying pass specific column name and use this column name in @Query but it doesn't work.

First I take the Path Param from the request. It will be my column name. Column name can be different, depends on what I chose.

@RestController
public class UserController {
  private final UserService UserService;

    @Autowired
    public UserController(UserService UsereService) {
        this.UserService = UserService;
    }
 
  @GetMapping(value = "/get/{columnName}")
    public List<String> getColumn(@PathParam("columnName") String columnName) {
        return userService.getColumn(columnName);
    }
}

Second I pass this column name to my service

@Service
public class UserService {

    private final UserRepository UserRepository;

    @Autowired
    public UserService(UserRepository UserRepository) {
        this.UserRepository = UserRepository;
    }

    public List<String> getColumn(String columnName) {
        return userRepository.getDistinctColumnByName(columnName);
    }

}

Third, I have my repository and here I have problem because my query doesn't work properly. I tried to many different way to change this query with nativeQuery and without nativeQuery but nothing change.

@Repository
public interface ValueRepository extends JpaRepository<Value, BigInteger> {
 
  @Query(value = "SELECT DISTINCT ?1 FROM test_table", nativeQuery = true)
    List<String> getDistinctColumnByName(String columnName);
}

Is there any way to use column name from request param and using it directly with DISTINCT ?

arson
  • 11
  • 2
  • from [similar question](https://stackoverflow.com/questions/42152468/how-to-add-custom-column-name-spring-data-jpa) you may get some idea to achieve your usecase – Shekhavat Mar 22 '22 at 08:36
  • This use case is how SQL injection attacks are allowed to happen. Use JPQL (or criteria queries) and at least JPA will validate the 'columnName' against the metadata it has on hand before allowing the database to run it. – Chris Mar 22 '22 at 16:21

0 Answers0