title: How to optimize hibernate method call in loop?
body: <p>I have a java web application built using spring+hibernate.</p>
  
  <p>I have code like this:</p>
  
  <pre><code>for (Account account : accountList){
  
      Client client = clientService.findById(account.getFkClient());  // fkClient is foreign key to Client
  
      if (client != null) {
          ...
          anObject.setName(client.getName());
          anObject.setAccountNo(account.getAccountNo());  
          ...
      }
      else {
          ...
          anObject.setAccountNo(account.getAccountNo());
          ...
      }
  
      ...
  }
  </code></pre>
  
  <p>accountList is a List of Account entity that retrieved from hibernate call. Inside the for loop, a Client entity is retrieved from account using hibernate call inside <strong>clientService.findById</strong> method.</p>
  
  <p>These are the class involved to the call:</p>
  
  <pre><code>public class ClientService implements  IClientService {
      private IClientDAO clientDAO;
  
      ...
  
      @Override
      public Client findById(Long id) throws Exception {
          return clientDAO.findById(id);
      }
  }
  
  public class ClientDAO extends AbstractHibernateDAO&lt;Client, Long&gt; implements IClientDAO {
  
      @Override
      public Client findById(Long id) throws Exception {
          return super.findById(id);
      }
  }
  
  public class AbstractHibernateDAO&lt;T,Y extends Serializable&gt; extends HibernateDaoSupport {
  
      protected Class&lt;T&gt; domainClass = getDomainClass();
  
      private Class&lt;T&gt; getDomainClass() {
          if (domainClass == null) {
              ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
              domainClass = (Class&lt;T&gt;) thisType.getActualTypeArguments()[0];
          }
          return domainClass;
      }
  
      public T findById(final Y id) throws SystemException {
          return (T) this.execute(new HibernateCallback&lt;T&gt;() {
  
              @Override
              public T doInHibernate(Session session) throws HibernateException, SQLException {
                  return (T) session.get(domainClass, id);
              }
          });
      }
  }
  </code></pre>
  
  <p>Note: clientService and clientDAO are spring beans object.</p>
  
  <p>My question is how to optimize the clientService.findById inside the loop with hibernate? I feel the findById call make the looping process become slower.</p>
  
  <p>The accountList usually contains 7000+ records, so I need something like pre-compiled query mechanism just like PreparedStatements in jdbc. Is it possible to do this with hibernate?</p>
  
  <p>Note: the code above has been simplified by removing unrelated parts, the method, variable and class name are made fictious for privacy reason. If you find a typo, please let me know in the comment section since I typed the code manually.</p>