Retrieving Hibernate query result as result set instead of list

前端 未结 3 1323
耶瑟儿~
耶瑟儿~ 2021-01-12 22:41

Heya, I m new to hibernate. I have to say it really simplifies everything for the SQL query. However, manipulating the returned result is a headache for me at the moment.

相关标签:
3条回答
  • 2021-01-12 23:14

    Ok, somehow I managed to make it work! Me so happy! For those who trying to find on how to manipulate the list returned by Hibernate query, basically what I did was..

    //previous code
    list = (List<MappedClass>)query.list();
    

    From there the list shall contain mapped class and you can access it by iterator and subsequently uses getter to retrieve the value. Example

    //previous code
    for (int i =0; i<list.size(); i ++) {
      String name;
      String id;
      name = list.get(i).getName();
      id = list.get(i).getId();
    
      //add your data manipulation here
    }
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-12 23:21

    You may need this if you have huge database and you can't fit List result into memory. Use scroll() instead of list():

    Query query = session.createQuery(query);
    query.setReadOnly(true);
    setFetchSize(Integer.MIN_VALUE); //MUST use Integer.MIN_VALUE, other value=fetch all
    ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
    // iterate over results
    while (results.next()) {
        Object row = results.get();
    }
    results.close();
    
    0 讨论(0)
  • 2021-01-12 23:37

    Slightly old thread but I cannot resist:

        // Code for iterating over a list of objects
        for(MappedClass mappedCless : list){
            String name = mappedClass.getName();
            String id = mappedClass.getId();
            // further logic
        }
    
    0 讨论(0)
提交回复
热议问题