What is the “proper” way to cast Hibernate Query.list() to List?

后端 未结 10 1648
梦谈多话
梦谈多话 2020-12-04 11:44

I\'m a newbie with Hibernate, and I\'m writing a simple method to return a list of objects matching a specific filter. List seemed a natural return t

相关标签:
10条回答
  • 2020-12-04 12:36

    Only way that work for me was with an Iterator.

    Iterator iterator= query.list().iterator();
    Destination dest;
    ArrayList<Destination> destinations= new ArrayList<>();
    Iterator iterator= query.list().iterator();
        while(iterator.hasNext()){
            Object[] tuple= (Object[]) iterator.next();
            dest= new Destination();
            dest.setId((String)tuple[0]);
            dest.setName((String)tuple[1]);
            dest.setLat((String)tuple[2]);
            dest.setLng((String)tuple[3]);
            destinations.add(dest);
        }
    

    With other methods that I found, I had cast problems

    0 讨论(0)
  • 2020-12-04 12:37

    You use a ResultTransformer like that:

    public List<Foo> activeObjects() {
        Session s = acquireSession();
        Query   q = s.createQuery("from foo where active");
        q.setResultTransformer(Transformers.aliasToBean(Foo.class));
        return (List<Foo>) q.list();
    }
    
    0 讨论(0)
  • 2020-12-04 12:39

    Just just using Transformers It did not work for me I was getting type cast exception.

    sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class)) did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.

    It worked for me when I make following changes When I have added sqlQuery.addScalar(-) each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");

    And I have join MYEngityName with NextEnity we cant just select * in the Query it will give array of Object in the return list.

    Below code sample :

    session = ht.getSessionFactory().openSession();
                    String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM  MYEngityName nft INNER JOIN NextEntity m on nft.mId  =  m.id where nft.txnId < ").append(lastTxnId)
                           .append(StringUtils.isNotBlank(regionalCountryOfService)? " And  m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
                           .append(" order by nft.txnId desc").toString();
                    SQLQuery sqlQuery = session.createSQLQuery(sql);
                    sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
                    sqlQuery.addScalar("txnId",Hibernate.LONG)
                            .addScalar("merchantId",Hibernate.INTEGER)
                            .addScalar("count",Hibernate.BYTE)
                            .addScalar("retryReason")
                            .addScalar("langCode");
                    sqlQuery.setMaxResults(maxLimit);
                    return sqlQuery.list();
    

    It might help some one. in this way work for me.

    0 讨论(0)
  • 2020-12-04 12:41

    Short answer @SuppressWarnings is the right way to go.

    Long answer, Hibernate returns a raw List from the Query.list method, see here. This is not a bug with Hibernate or something the can be solved, the type returned by the query is not known at compile time.

    Therefore when you write

    final List<MyObject> list = query.list();
    

    You are doing an unsafe cast from List to List<MyObject> - this cannot be avoided.

    There is no way you can safely carry out the cast as the List could contain anything.

    The only way to make the error go away is the even more ugly

    final List<MyObject> list = new LinkedList<>();
    for(final Object o : query.list()) {
        list.add((MyObject)o);
    }
    
    0 讨论(0)
提交回复
热议问题