码:
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<CrbtSubMasterDemo> itr = query.list(); session.getTransaction().commit(); for (CrbtSubMasterDemo pojo : itr) {//excepion line System.out.println("[" + pojo.getMobile() + "]"); } } catch (Exception e) { e.printStackTrace(); } }
CrbtSubMasterDemo 与数据库一起映射。当我尝试运行它时,它显示以下异常:
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<CrbtSubMasterDemo> itr = query.setResultTransformer(Transformers.aliasToBean(CrbtSubMasterDemo.class) ).list(); ##No need to commit the transaction. }
它将您查询转换为CrbtSubMasterDemo