Search code examples
javahibernatehibernate-native-query

How to avoid executing the query multiple times?


Say I have this nativeQuery in my DAO:

SELECT a, b, c FROM table

which returns all the values I need.

The problem is I have too many results and I need the query to run only once instead of running for every single row found.

I'm retrieving the query result and setting all the values into a class (value object) called Class like this:

public List<Class> listClass() {

    List<Class> listaObjs;

    String nativeQuery = "SELECT a, b, c FROM table";
    SQLQuery q = getSession().createSQLQuery(nativeQuery);

    int totalRecords = q.list().size();
    System.out.println("Total records: " + totalRecords);

    listaObjs = q.list();

    // For every ROW in query Result
    for (int i = 0; i < totalRecords; i++) {
        Object[] objs = (Object[]) q.list().get(i);
        Class item = new Class();

        // For every COLUMN in that ROW
        for (Object obj : objs) {
            item.setValueA((String) objs[0]);
            item.setValueB(((String) objs[1]));
            item.setValueC(((String) objs[2]));
            listaObjs.add(item);
        }
    }
    return listaObjs;
}

I'm a bit stuck here because I've never treated this Object[] to Class casting before.


Solution

  • Change the below lines

    // For every ROW in query Result
    for (int i = 0; i < totalRecords; i++) {
        Object[] objs = (Object[]) q.list().get(i);
    

    Use

    List<Object[]> objArr = q.list();
    // For every ROW in query Result
    for (int i = 0; i < totalRecords; i++) {
        Object[] objs = (Object[]) objArr.get(i);