java.lang.ClassCastException:[Ljava.lang.Object; 无法强制转换为className
码:
public void getDetails() { try { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20"; Query query = session.createQuery(hql); List itr = query.list(); session.getTransaction().commit(); for (CrbtSubMasterDemo pojo : itr) {//excepion line System.out.println("[" + pojo.getMobile() + "]"); } } catch (Exception e) { e.printStackTrace(); } }
CrbtSubMasterDemo与数据库进行pojo映射。 当我尝试运行它时,它会给出以下exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.telemune.demoPojo.CrbtSubMasterDemo at com.telemune.demoHibernate.QueryTester.getDetails(QueryTester.java:57) at com.telemune.demoHibernate.QueryTester.main(QueryTester.java:23)
问题是query.list()返回pojo类的对象列表。 那为什么是这个例外。 我是Hibernate的新手,抱歉,如果这是一个愚蠢的问题。
先生,很多时候用户都面临着这种要求。 Hibernate有ResultTransformer来转换Object中的hql / sql。
public CrbtSubMasterDemo{ private Stirng mobile; private String password; public CrbtSubMasterDemo(){ -------------- } #####after setting the transation set whichever columns you are selecting should be given as name of property of your object String hql = "select c.mobile as mobile, c.password as password FROM CrbtSubMasterDemo c where rownum<20"; Query query = session.createQuery(hql); List itr = query.setResultTransformer(Transformers.aliasToBean(CrbtSubMasterDemo.class) ).list(); ##No need to commit the transaction. }
它会将您的查询转换为CrbtSubMasterDemo
当你写这个:
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
您的结果集不是CrbtSubMasterDemo
List
试着写:
String hql = "select FROM CrbtSubMasterDemo c where rownum<20";
另一种方法是定义一个新的CrbtSubMasterDemo构造函数,你只传递两个字段c.mobile, c.password
所以你的查询变为:
String hql = "select new " + CrbtSubMasterDemo.class.getName() + "(c.mobile, c.password) FROM CrbtSubMasterDemo c where rownum<20";
如果您遵循此解决方案,请记住添加默认构造函数(不带参数),因此在您的pojo中您有:
public CrbtSubMasterDemo(String mobile, String password) { this.mobile = mobile; this.password = password }
和
public CrbtSubMasterDemo() { }
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20"; Query query = session.createQuery(hql);
结果将是List
List
当然,如果mobile
和password
是字符串。 您可以使用转换器将结果直接转换为CrbtSubMasterDemo
。
Hibernate 3.2:用于HQL和SQL的变换器
FluentHibernateResultTransformer
不要直接转换“query.list();”的结果 到CrbtSubMasterDemo列表。 作为query.list()返回对象列表。 迭代收到的对象列表并逐个投射到列表中的CrbtSubMasterDemo列表