Skip to content
Advertisement

JPA Query. Path array of parameters that need to be selected

I need to choose dynamically which parameters should be in query output. Is there any way to do something like that:

JavaScript

For example I have Entity User with name, surname, address, age. In one case I want to choose only name, in other sername, age and address. And e.t.c

Advertisement

Answer

You can create interfaces to represent a View like the following:

JavaScript

and then put it as the return value in your repository:

JavaScript

You can also implement a dynamic projection the following way:

JavaScript

and call it like

JavaScript

Read more about projection here: https://www.baeldung.com/spring-data-jpa-projections

Edit

You can be truely dynamic if you use javax.persistence.Tuple as return value in your interface:

JavaScript

However you have to extract the data yourself then:

JavaScript

However that still selects all fields from the database. If you truely want dynamic sql queries you can call EntityManager to create a dynamic SQL:

JavaScript

If you do that make sure to not be vulnerable for SQL injection!

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement