Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"java.lang.String cannot be cast" Error in Hibernate

 
Maya sekar
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,


I was working on a simple Hibernate sample program,


something I copied off RoseIndia. From what i can see the code is error free, but when I run it I get the following error msg,


Hibernate: select bean0_.username as col_0_0_ from bean bean0_ where bean0_.id='3'
java.lang.String cannot be cast to my.apps.Bean

I initially assumed my HQL Query was wrong, but when I paste the query directly in the database and run it, I get the resultset... but through the progam I get the error msg pasted above. Can anyone help me figure out what I have done wrong?

Thank you
 
Riaan Nel
Ranch Hand
Posts: 160
IntelliJ IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Maya

Look at the following two lines of your code;

You are selecting b.userName (which looks like a String), but you are trying to cast that String to your Bean class. If you execute an HQL query with a single field, the returned list will contain objects of the type of that field. I.e., you are getting a list of String objects.

If you want to select Bean objects, your query should look like this;


Cheers,
Riaan
 
Maya sekar
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much. I understand now...

 
Riaan Nel
Ranch Hand
Posts: 160
IntelliJ IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are most welcome!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic