Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I got this error while retrieving data from the database.

java.lang.String cannot be cast to com.rahul.model.MyUser] with root cause java.lang.ClassCastException: java.lang.String cannot be cast to com.rahul.model.MyUser.

IntegraController.java

@RequestMapping("/users")
public  ModelAndView users()
{
    List<MyUser> p =dq3.usersA2();
    for (MyUser p1 : p){
        System.out.println(p1.getUsername());
    }
    ModelAndView m=new ModelAndView();
    m.setViewName("users");
    m.addObject("list",p);
    return m;
}

Dao.java

@Transactional
@Repository
public class Dao {
    private Session session;
    @Autowired
    private MyUser u;
    @Autowired
    private Post p;
    @Autowired
    private Person per;
    @Autowired
    private Roles r;
    @Autowired
    private Answer a;
    @Autowired
    private HibernateTemplate ht;

    public  List<MyUser> usersA2()
    {
        List<MyUser> p2;   
        p2 = ht.executeFind(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(Session sn) throws HibernateException, SQLException {
                List<MyUser> p1 =sn.createQuery("SELECT E.username FROM MyUser E").list();
                return p1;
            }   
        });
        return p2;
    }
share|improve this question
3  
please indent your code.. the indentation/formatting is horrible! –  sanbhat Jul 25 '13 at 11:31
    
Why your title says the error is one and in the question the error is different? Please fix your question. –  m0skit0 Jul 25 '13 at 11:33
4  
But everybody else does. –  null Jul 25 '13 at 11:36
3  
Welcome to SO, please avoid the screaming. Also: Great questions will usually get great responses - a great question consists of a proper title and neatly formatted source... amongst other things. –  reto Jul 25 '13 at 11:38
2  
1. Please remember that StackOverflow needs to maintain standard of the questions posted. 2. Please don't scream. These guys are doing you a favor by spending time to read your question and write an answer. Apart from that, welcome !! :) –  Little Child Jul 25 '13 at 11:47

1 Answer 1

up vote 3 down vote accepted

Your query looks like this: "SELECT E.username FROM MyUser E"

The E.username part will return a list of username Strings. It should be From MyUser to get MyUser objects.

Something like:

List<MyUser> p1 =sn.createQuery("FROM MyUser").list();
share|improve this answer
    
List<MyUser> p1 =sn.createQuery("FROM MyUser u Where u.username=:user").list(); this also work Thanks............ –  Shaikh Mohsin Jul 30 '13 at 8:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.