-10

从数据库中检索数据时出现此错误。

java.lang.String cannot be cast to com.rahul.model.MyUser] 根本原因 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;
}

道.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;
    }
4

1 回答 1

3

您的查询如下所示:"SELECT E.username FROM MyUser E"

E.username部分将返回用户名字符串列表。应该是From MyUser获取MyUser对象。

就像是:

List<MyUser> p1 =sn.createQuery("FROM MyUser").list();
于 2013-07-25T11:35:14.313 回答