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

后端 未结 10 1665
梦谈多话
梦谈多话 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: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.

提交回复
热议问题