2012-03-01 41 views
1

我使用下面的查询在休眠无法施展HibernateQuery resuly列表对象类

Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 
session.beginTransaction(); 
Query q = session.createSQLQuery("select name,addr1,addr2,postal_code,country,email," + 
       "tel1,tel2,HeadOffice_id,Subscription_id from Restaurant " + 
       "where id=" +id); 
session.getTransaction().commit(); 
Restaurant rest = (Restaurant)result.get(0); 

从数据库中取数据但这回例外

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.hibernate.model.Restaurant 

我也试过这种方式,以及不知道什么在做

AnnotationConfiguration config = new AnnotationConfiguration(); 
config.addAnnotatedClass(Restaurant.class); 
SessionFactory factory= config.configure().buildSessionFactory(); 
Session session =factory.getCurrentSession(); 
session.beginTransaction(); 
Query q = session.createSQLQuery("select name,addr1,addr2,postal_code,country,email," + 
        "tel1,tel2,HeadOffice_id,Subscription_id from Restaurant " + 
        "where id=" +id); 
java.util.List<Restaurant> result = (List<Restaurant>)q.list(); 
session.getTransaction().commit(); 
Restaurant rest = (Restaurant)result.get(0); 

我再次得到同样的例外。我如何用hibernate做到这一点?

谢谢

+0

它说,它不能施放'[对象]''到Restaurant',可能是因为你选择了你的餐厅 – 2012-03-01 14:19:49

+0

的各个属性对不起,u能解释一下吗?谢谢 – Zach 2012-03-01 14:21:42

回答

5

您的查询不会返回Restaurant实体的实例。它从这个实体返回单个字段。这样的查询的结果是List<Object[]>,每个Object[]包含所有选择的字段。

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql-select

查询可以返回多个对象和/或属性在Object []数组:

如果你希望你的查询餐厅的returninstances,它应该是

select r from Restaurant r where id = :id 

而且请不要使用连接来传递您的参数。使用命名参数作为上述查询。

+0

我尝试过的方式,它的工作原理查询q = session.createQuery(“从餐厅其中id =:id”); \t q.setInteger(“id”,id);我可以使用createSQLQuery并获得相同的结果吗? – Zach 2012-03-01 14:46:55

+1

为什么你想使用SQL查询,因为这个HQL查询做你想要的? – 2012-03-01 15:34:02

0

简单:

Restaurant rest = (Restaurant)session.get(Restaurant.class, id); 
相关问题