1

I am trying to add table name dynamically in my query which returns List<object[]> as return type

I am currently appending the table name inside the query I don't think that's the optimal solution .Is there any other solution better than this?

public List<Object[]> getResult(String tableName){

try {
        Session session = currentSession();
        Query query = session.createSQLQuery("select * from "+tableName);
        return query.list();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        closeSession();
    }

}

2 Answers2

1

How about doing it the other way around? Instead of giving a table name and getting corresponding type, give a corresponding type and let code figure out table name.

public <T> List<T[]> getResult(Class<T> type){
    try {
        Session session = currentSession();
        Query query = session.createSQLQuery("select * from " + type.getName() + "s");
        ArrayList<T> result = new ArrayList();
        for(Object o : query.list())
            result.add((T) o);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        closeSession();
    }
}

type is class used to represent records in the table. This example assumes that in database tables only have additional "s" in their name, so if in Java you have class SomeObject and corresponding table is some_objects you might want to do some more Java-style names to SQL-style names conversion then type.getName() + "s".

Anyway - this should return you a list of elements casted to correct type, when you call getResult(SomeObject.class);

Miku
  • 567
  • 6
  • 15
1

In general if you need a SQL query with variable table name you're doing something wrong.

So it would be interesting what kind of program you are writing.

I can only think of a SQL database viewer or a database dumper which would need variable table names.

Also your method seems vulnerable to a SQL injection (unless you checked the table name before calling the method).

I am personally only using prepared queries when passing any variable to a SQL query. Your query as prepared statement would look like "SELECT * FROM ?". You can try if it is supported by your database. But it should not be because such a kind of query is only needed in very rare cases.

zomega
  • 1,538
  • 8
  • 26