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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With