java.lang.ClassCastException:[Ljava.lang.Object; 无法强制转换为entity.UserEntity

我想在hibernate中查询两个表。 用户实体中的featch 3表(用户 – 角色 – 配置文件)。 用hql查询:

query= "select ue, ue.roleEntity.roleId from UserEntity ue ,RoleEntity re fetch all properties where ue.roleEntity.roleId=re.roleId and ue.username ='reza' and ue.password='123456'"; 

并运行查询:

  try { sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.getCurrentSession(); transaction = session.beginTransaction(); userEntityList = (List) session.createQuery(query).list(); transaction.commit(); } catch (HibernateException e) { try { throw new DaoException("Fetal exception in", e); } catch (DaoException e1) { e1.printStackTrace(); } } 

userentity类:这个类是geteer和seter:

 public class UserEntity { private int userId; private long personalCode; private String username; private String password; private short active; private String question; private String passive; private ProfileEntity profileEntity; private RoleEntity roleEntity; 

用于userEntity.hbm.xml的hibernate maping

                         

和类hibernateutil用于创建sesstion:

  import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static { try { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); } catch (Throwable th) { System.err.println("Enitial SessionFactory creation failed" + th); throw new ExceptionInInitializerError(th); } } /** * @return */ public static SessionFactory getSessionFactory() { return sessionFactory; } } 

因为您正在使用多选投影,所以实际上是在获取对象数组,因此您需要将查询结果处理逻辑更改为:

 List tuples = (List) session.createQuery(query).list(); for(Object[] tuple : tuples) { UserEntity ue = tuple[0]; Number roleId = tuple[1]; }