Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

hibernate - java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to className

Code:

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 is pojo mapped with the db. When I try to run it, it gives following 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)

The question is query.list() is returning the list of objects of pojo class. Then why is this Exception. I am new to Hibernate, sorry if its a silly question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

When you write this:

String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";

Your result set is not a List of CrbtSubMasterDemo

Try to write:

String hql = "select FROM CrbtSubMasterDemo c where rownum<20";

Another way is define a new constructor of CrbtSubMasterDemo where you pass only two fields c.mobile, c.password

so your query becomes:

String hql = "select new " + CrbtSubMasterDemo.class.getName() + "(c.mobile, c.password) FROM CrbtSubMasterDemo c where rownum<20";

If you follow this solution, remeber to add a default constructor too (without parameters), so in your pojo you have:

public CrbtSubMasterDemo(String mobile, String password) {
    this.mobile = mobile;
    this.password = password
}

and

public CrbtSubMasterDemo() {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...