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

Time:11-18

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

CodePudding user response:

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!

  • Related