从 table 检索地图<String,<T>>

Retrieve a Map<String,<T>> from a table

我读了一些像this and this这样的信息性帖子,但我仍然很困惑。

Hibernate 版本是 4.3.11 MySQL 帐户 table 是:

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 @return A java.util.Map 以账户引用为键,账户实体为值 @throws DaoException

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. 线程声明 查询将 return 将 return 地图列表 - 我不明白这个

我收到了 this forum thread 的回复。

You are trying to cast a List into a Map. Check out the map() select syntax. The Map is supposed to wrap the ResultSet, but the query returns a List.

I suggest you return a List and then build the Map using a simple iteration.