从数据库中检索数据时出现此错误。
java.lang.String无法根据原因强制转换为com.rahul.model.MyUser] java.lang.ClassCastException:java.lang.String无法强制转换为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;
}
答案 0 :(得分:3)
您的查询如下所示:"SELECT E.username FROM MyUser E"
E.username
部分将返回用户名字符串列表。 <{1}}获取From MyUser
个对象应该是MyUser
。
类似的东西:
List<MyUser> p1 =sn.createQuery("FROM MyUser").list();