Query with dynamic column spring data

3

I need to perform a select using the @Query of spring data, however I need to pass the column name by parameter

Example:

@Query("SELECT g FROM Grupo g where g.? = ?") 
Page<Grupo> findTeste(String campo, String valor);

To call method I wanted to pass the column name as follows:

//Pseudo code
page = grupoService.findTeste("id", "1");
page = grupoService.findTeste("nome", "asdf");

Is it possible to build some method like this in spring data?

    
asked by anonymous 22.08.2016 / 14:37

2 answers

1

In the documentation itself you have an example of @Query with NamedParameters:

-

  

5.3.6. Using named parameters

     

By default, JPA will use position based parameter binding   as described in all the above samples. This makes query methods a   little error prone to refactoring around the parameter position. To   solve this issue you can use @Param annotation to give a method   parameter to a concrete name and bind the name in the query. Example 52.   Using named parameters

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
  User findByLastnameOrFirstname(@Param("lastname") String lastname,
                                 @Param("firstname") String firstname);
}
  

Note that the method parameters are switched according to the   occurrence in the query defined.

link

    
13.10.2016 / 21:18
0

I think in this case you can not do this using Spring Data.

But you can create a class for example: CustomRepository

In this class you can use the EntityManager and execute the query as you want, for example:

@PersistenceContext
protected EntityManager manager;

public Grupo findTeste(String campo, String valor) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT g FROM Grupo g where g.").append(campo).append(" = :").append(valor);
    String query = sb.toString();
    return manager.createQuery(query, Grupo.class).getSingleResult();
}
    
22.05.2017 / 02:24