'Is there a way to dynamically set columns to retrieve in query using spring JPA?

I'm using spring boot and I have some queries in a separate properties file that I want to modify to allow a user to select which data columns to return from the db.

Right now the queries look like this:

select * from table where val=(:val);

But I want something like this:

select (:listOfColumnNames) from table where val=(:val);

I want to keep using JPA so is there any workaround to do this/get a similar functionality?



Solution 1:[1]

You can use native query like below in jpa however this is not safe way to do it .As this code is vulnerable to risk .

@Query(
  value = "select "+listOfColumnNames+"from table where val= "+input+", 
  nativeQuery = true)
Collection<User> findData();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dhiraj Surve