Bogdan Lashkov Bogdan Lashkov - 3 months ago 43
SQL Question

QueryDSL request with parameters, is it possible?

In SQL it is very simple to make parameterized query using string concatenation. Example, where I'm getting necessary columns from the DB table according preset parameters (strings with columns' names)

String id_column = "id", city_column = "city", streetname_column ="streetname", housenumber_column = "housenumber"; //Parameters
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT "+id_column+","+streetname_column+" FROM address" ); //How do the same in QueryDSL?
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++){
System.out.print(rsmd.getColumnName(i+1)+" ");
}
while ( rs.next() ) {
System.out.print("\n");
for (int i = 0; i < rsmd.getColumnCount(); i++){
System.out.print(
rs.getString(rsmd.getColumnName(i+1)) + " "
);
}
}


How can i do the same with this (you also can make your own example) QueryDSL request:

List<Address> q1=queryFactory.selectFrom(address)
.fetch();


In this query I am getting whole table.

Answer

Finally, I have found an answer. The solution is located at this page: Examples of using play.db.jpa.JPAApi

And in the context of my question, solution is following:

package controllers;
import play.db.jpa.JPAApi;
import play.db.jpa.Transactional;
import javax.inject.Inject;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

public class TestingReportsDep{

private JPAApi jpaApi;
@Inject
public TestingReportsDep(JPAApi jpaApi) {
    this.jpaApi = jpaApi;
}
Object[] tempObj;

@Transactional
public void resolving_requests) {
    String id_column = "id", city_column = "city", streetname_column ="streetname", housenumber_column = "housenumber"; //Parameters
    String request="SELECT "+id_column+","+streetname_column+" FROM address;";
    jpaApi.withTransaction(entityManager -> {
        Query query = entityManager.createNativeQuery(request);
        int ResultsAmount = query.getResultList().size();
        List Result = query.getResultList();
        System.out.print("\n\n\nNew super query by Bogdan:\n");

        for(int i=0; i< ResultsAmount; i++){
            tempObj = (Object[]) Result.get(i);

            System.out.print(tempObj[0]+" "+tempObj[1]+"\n");
        }
        return null;
    });
 }
}