用Spring整合Hibernate去实现对mysql数据表信息查询时,由hql语句查询到的一个Object强制转换为一个pojo不能成功。
TeacherDaoImpl.java代码
public Teacher findByNo(String no) {
String hql="select t.tno,t.tname,t.tpassword,t.tgender,t.tbirthday,t.tbelong,t.tduty,t.ttaketime,t.ttel from Teacher t where t.tno=?";
Teacher teacher=(Teacher)getSession().createQuery(hql).setParameter(0,no).uniqueResult(); //报错
return teacher;
数据库已连接成功,实体类Teacher也贴出来吧
@Entity
@Table(name="Teacher")
public class Teacher {
public Teacher() {
super();
// TODO Auto-generated constructor stub
}
@Id
@Column(name="tno")
private String tno;
@Column(name="tname")
private String tname;
@Column(name="tpassword")
private String tpassword;
@Column(name="tgender")
private String tgender;
@Column(name="tbirthday")
private Date tbirthday;
@Column(name="tbelong")
private String tbelong;
@Column(name="tduty")
private String tduty;
@Column(name="ttaketime")
private Date ttaketime;
@Column(name="ttel")
private String ttel;
public String getTno() {
return tno;
}
public void setTno(String tno) {
this.tno = tno;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getTgender() {
return tgender;
}
public void setTgender(String tgender) {
this.tgender = tgender;
}
public String getTbelong() {
return tbelong;
}
public void setTbelong(String tbelong) {
this.tbelong = tbelong;
}
public String getTduty() {
return tduty;
}
public void setTduty(String tduty) {
this.tduty = tduty;
}
public String getTtel() {
return ttel;
}
public void setTtel(String ttel) {
this.ttel = ttel;
}
public Date getTbirthday() {
return tbirthday;
}
public void setTbirthday(Date tbirthday) {
this.tbirthday = tbirthday;
}
public Date getTtaketime() {
return ttaketime;
}
public void setTtaketime(Date ttaketime) {
this.ttaketime = ttaketime;
}
public String getTpassword() {
return tpassword;
}
public void setTpassword(String tpassword) {
this.tpassword = tpassword;
}
@Override
public String toString() {
return "Teacher [tno=" + tno + ", tname=" + tname + ", tpassword=" + tpassword + ", tgender=" + tgender
+ ", tbirthday=" + tbirthday + ", tbelong=" + tbelong + ", tduty=" + tduty + ", ttaketime=" + ttaketime
+ ", ttel=" + ttel + "]";
}
}
报错 :
HTTP Status 500 - Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to a.model.Teacher
HQL 语句不对,
select t.tno,t.tname,t.tpassword,t.tgender,t.tbirthday,t.tbelong,t.tduty,t.ttaketime,t.ttel from Teacher t where t.tno=?
这个只能出来 object[], 要出 Teacher 对象,只能
select t from Teacher t where t.tno=?
其中 select 只能是 Teacher 对象,不能是其他的。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。