代码:
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 与数据库进行pojo映射。 当我尝试运行它时,它会给出以下异常:
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的新手,对不起,如果这是一个愚蠢的问题。
答案 0 :(得分:3)
当你这样写:
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
您的结果集不是List
CrbtSubMasterDemo
尝试写:
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() {
}
答案 1 :(得分:3)
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
结果为List<Object[]>
List<Object[]> itr = query.list();
for (Object[] row : itr) {
System.out.println(String.format("mobile:%s, password:%s", row[0], row[1]));
}
当然,如果mobile
和password
是字符串。您可以使用转换器将结果直接转换为CrbtSubMasterDemo
。
答案 2 :(得分:1)
不要直接转换&#34; query.list();&#34;的结果。到CrbtSubMasterDemo列表。作为query.list()返回对象列表。迭代收到的对象列表并逐个投射到列表中的CrbtSubMasterDemo列表
答案 3 :(得分:1)
先生,很多时候用户都面临着这种要求。 Hibernate有ResultTransformer来转换对象中的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