This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Object Relational Mapping and the fly likes Struts2 and Hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Struts2 and Hibernate" Watch "Struts2 and Hibernate" New topic
Author

Struts2 and Hibernate

Hardik Patel p
Ranch Hand

Joined: Jan 23, 2014
Posts: 32

hi,

str="select * from stud where id=1"; // this will fetch one record.

Student s = (Student) session.createQuery(str);

system.out.println( s.getid + " " + s.getname);


ERROR :

org.hibernate.impl.QueryImpl cannot be cast to Student


Note : Inshort , Its ok if we use iterate if query return multiple records. In above query return only one record so I dont want use iterator. and like this (classname.class, 1). Request all user to solve this.

Many thanks
Hardik

Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8876
    
    8

Your code cannot possibly work as createQuery returns a Query instance, not a database entity (see the documentation). You still need to execute the query to get the results.
However, since you want to find a single entity, you should probably look at something like this.
Since this has nothing to do with Struts, I'll move it to the Hibernate forum if you have any further questions.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Anil Sable
Greenhorn

Joined: Jan 08, 2012
Posts: 7
Hey , looks you want to retrived one record from database with perticular id

try to use Criteria for such purpose



consider HibernateUtil is your helper class to obtain sessionFactory


then code looks like


Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Criteria cr = session.createCriteria(Student.class);

cr.add(Restrictions.eq("id",1));

Student obj = cr.uniqueResult();

then perform what ever you want to perform


if you think that multiple student will retrive then you could use

List<Student> list = cr.list();
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Struts2 and Hibernate