Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom column name Spring Data JPA? [duplicate]

I have lots of column in my DB and don't want to write custom queries for all of them so consider the below method runs for every column name dynamicaly which i give as column_name. Is something like this possible or are there any other way to do that?

      @Query("select #column_name from Item Where #column_name like %?2% ")
      List<Item> getUniqueColumn(String column_name,String column_text);

By the way in spring documantation this case not mentioned.

like image 242
C.T Avatar asked Oct 18 '25 13:10

C.T


1 Answers

You can only pass values that you are expecting as parameters to your HQL queries. You can't pass column or table names.

Hibernate is basically working here with a PreparedStatement, and a statement cannot be prepared where the table / columns being queried for are not known yet.

You would have to write some String replacement logic or build your query with the Criteria API

List<Object> getUniqueColumn(String column_name,String column_text){
        StringBuilder query = new StringBuilder();
        query.append("select #column_name ");
        query.append("from Item ");
        query.append("where #column_name like %?1%");

        query = query.toString("#column_name", column_name);

        session.createQuery(query).setString(1, column_text).list();
}

Also remember that what you are doing here is a projection and you will not get a List of Item but a List of Objects.

like image 126
Maciej Kowalski Avatar answered Oct 22 '25 08:10

Maciej Kowalski