SSH框架里用SQL查出的Object对象不能转化为映射类是为什么啊
User表和Department两张表 是多对一的关系,Department的主键是User的外键
SSH框架中hibernate的配置文件如下
<hibernate-mapping>
<class name="com.pmsystem.model.authority.Department" table="t_department">
<id name="dptId">
<generator class="native"/>
</id>
<property name="dptName">
<column name="dptName" not-null="true" />
</property>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.pmsystem.model.authority.User" table="t_user">
<id name="userId">
<generator class="native"/>
</id>
<property name="loginName">
<column name="loginName" not-null="true" />
</property>
<property name="password">
<column name="password" not-null="true" />
</property>
<property name="userName">
<column name="userName" not-null="true" />
</property>
<many-to-one name="Department" class="com.pmsystem.model.authority.Department" column="dptId" cascade="save-update"></many-to-one>
</class>
</hibernate-mapping>
public List<User> getLoginUser(final User user) {
//查询登陆的sql语句必须是fianl类型的
final String loginSql = "select * from t_user u where u.loginName = ? and u.password = ?";
List<User> result = this.getHibernateTemplate().executeFind(new HibernateCallback(){
public List<User> doInHibernate(Session session) throws
HibernateException,
SQLException {
SQLQuery query = session.createSQLQuery(loginSql);
query.setString(0, user.getLoginName());
query.setString(1, user.getPassword());
//获得结果
List<Object> temp = (List)query.list();
List<User> t = (List)temp ;
return t;
}
});
return result;
}
sql查出来的对象放在list里,第0个里面是Object类型的,转换成User类型就报错
或者直接List<User> temp = query.list();
返回List<User> 类型的,虽然temp不为空,显示里面是User类型的,但是只要用sett和gett去取里面的值就报类型转换错误
------解决方案--------------------
//.addEntity(User.class)作用是将object[]转换成指定为类
SQLQuery query = session.createSQLQuery(loginSql).addEntity(User.class);
试试这个看行不。