0

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

@Query(value = "select params = :arrayOfParams from myTable", nativeQuery = true)
User findparamsAll(@Param("arrayOfParams") List<String> params);

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

1
  • findAllByParamIn(Iterable<String> params) Commented Nov 17, 2022 at 12:19

1 Answer 1

1

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

public interface UserView {
    String getName();
}

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

UserView findAll();

You can also implement a dynamic projection the following way:

T findAll(Class<T> type);

and call it like

userRepository.findAll(UserView.class)
userRepository.findAll(User.class)

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:

Tuple findAll();

However you have to extract the data yourself then:

tuple.get("NAME", String.class)

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:

entityManager.createQuery("select ..."), Tuple.class).getResultList();

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answering, but I think i need bit different. For example I have Entity User with name, sername, address, age. In one case I want to choose only name, in other surname, age and address. And e.t.c In article u send, I guess I need to write to many different interface to emulate dynamically output of rows
I added some truly dynamic possibilities, but since Java doesn't really have dynamic objects anyway I am not sure if that's really a good way to do things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.