2016-05-18 33 views
0

我讀了一些內容豐富的帖子,如thisthis但我仍然感到困惑。檢索地圖<String,<T>>從表

Hibernate的版本是4.3.11 MySQL的客戶表:

Field   Type   Null Key 
Id    int(11)   NO  PRI 
Reference  varchar(20)  NO  UNI  
Balance   decimal(10,5) NO   
Currency  varchar(3)  NO   
Valid   tinyint(1)  NO   
Type   varchar(20)  YES   

的AccountDaoImpl方法:

@Override 

接受有效帳戶引用的集合 @param accountReferences @返回一個java.util.Map,其帳戶引用爲key,Account實體的值爲 @throws DaoExce ption

public Map<String, Account> getAccountsByReferences(Collection<String> accountReferences) throws DaoException { 
     // TODO Auto-generated method stub 

     if (accountReferences == null || accountReferences.isEmpty()) { 
      return null; 
     } 

     if (accountReferences.size() > Constants.MAX_ACCOUNTS_SIMULT) { 
      throw new DaoException("Please query " + Constants.MAX_ACCOUNTS_SIMULT + " at a time"); 
     } 

     String accountByRefSQL = "SELECT new map(acc.reference,acc) FROM Account acc WHERE acc.reference IN (:accountReferences)"; 

     Session session = null; 
     try { 
      session = HibernateUtil.getSessionFactory().openSession(); 

      Query query = session.createQuery(accountByRefSQL).setParameterList("accountReferences", accountReferences); 

      return findMany(query); 

     } catch (DaoException daoException) { 
      log.error("DaoException in AccountDaoImpl.findAccountByReference(...)", daoException); 
      throw daoException; 
     } catch (HibernateException e) { 
      log.error("HibernateException in AccountDaoImpl.findAccountByReference(...)", e); 
      throw new DaoException(e.getMessage()); 
     } finally { 
      session.close(); 
     } 
    } 

的findMany()方法是在父GenericDao:

public List<T> findMany(Query query) throws DaoException { 
     try { 
      List<T> t; 
      t = (List<T>) query.list(); 
      return t; 
     } catch (HibernateException hibernateExecption) { 
      log.error("Hibernate Exception in GenericHibernateDaoImpl.findMany(...)", hibernateExecption); 
      throw new DaoException(hibernateExecption.getMessage()); 
     } catch (RuntimeException runtimeException) { 
      log.error("RuntimeException in GenericHibernateDaoImpl.findMany(...)", runtimeException); 
      throw new DaoException(runtimeException.getMessage()); 
     } 

    } 

有兩個問題:

  1. 按照我所提到的線程,調用正確的是(我不知道如何!)
  2. 線程狀態,查詢將返回將返回一個地圖列表 - 我不明白這

回答

0

我從this forum thread得到了答覆。

您正試圖將列表投射到地圖中。 Check out the map()選擇 語法。 Map應該包裝ResultSet,但查詢 返回一個List。

我建議你返回一個列表,然後使用簡單的 迭代構建地圖。

相關問題