1

I am using the following query to fetch data from db in hibernate

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);

But this is returning exception

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

I also tried this way as well not sure whats doing

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);

Again I am getting the same exception. How can i do this with hibernate?

Thanks

2
  • It says that it cannot cast Object[] to Restaurant, probably because you have selected individual attributes of your Restaurant Commented Mar 1, 2012 at 14:19
  • Sorry, Can u explain please? Thanks Commented Mar 1, 2012 at 14:21

2 Answers 2

5

Your query doesn't return instances of the Restaurant entity. It returns individual fields from this entity. The result of such a query is a List<Object[]>, each Object[] containing all the selected fields.

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

Queries can return multiple objects and/or properties as an array of type Object[]:

If you want your query to returninstances of Restaurant, it should be

select r from Restaurant r where id = :id

And please, don't use concatenation to pass your parameter. Use named parameters as the above query.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried thius way and it works Query q = session.createQuery("from Restaurant where id = :id"); q.setInteger("id", id); Can I use createSQLQuery and achieve the same result?
Why do you want to use a SQL query since this HQL query does what you want?
0

as simple as:

Restaurant rest = (Restaurant)session.get(Restaurant.class, id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.