在迭代从HQL中退出的列表
时,我收到了ClassCastException在这一行
UserPojo u=(UserPojo)userList.get(0);
UserDao.java
public class UserDao
{
Session session = null;
Transaction tx=null;
public int validateUser(UserManagedBean user)
{
int validateFlag=-1;
try
{
tx = session.beginTransaction();
Query q = session.createQuery("select user1.userId, user1.userName, user1.password from UserPojo user1 where user1.userName=:userName and user1.password=:password");
//Query q=session.getNamedQuery("validateUser");
//Query q=session.getNamedQuery("proc_validateUser");
q.setParameter("userName", user.getUserName());
q.setParameter("password", user.getPassword());
List<UserPojo> userList = q.list();
//List<UserPojo> userList = (List<UserPojo>)q.list();
int rowCount = userList.size();
if (rowCount == 1)
{
UserPojo u=(UserPojo)userList.get(0);
System.out.println("U.userId:"+u.getUserId());
//user.setUserId(userList.get(0).getUserId());
validateFlag = 1;
}
else if (rowCount == 0)
{
validateFlag = 0;
}
else if (rowCount > 1)
{
validateFlag = -1;
}
tx.commit();
}
catch (HibernateException e)
{
LOG.logp(Level.SEVERE, "UserDao", "validateUser", "Caught HibernateException During User Validity Check", e);
try
{
tx.rollback();
}
catch(HibernateException ex)
{
LOG.logp(Level.SEVERE, "UserDao", "validateUser", "Caught HibernateException While Rolling Back Transaction", ex);
}
}
return validateFlag;
}
public UserDao()
{
session = HibernateUtil.getSessionFactory().getCurrentSession();
}
private static final Logger LOG = Logger.getLogger(UserDao.class.getName());
}
答案 0 :(得分:0)
您在查询中选择了3件事:
select user1.userId, user1.userName, user1.password...
因此,您的查询将返回List<Object[]>
而不是UserPojo
尝试这样的事情:
select user1 from UserPojo user1 where user1.userName=:userName and
user1.password=:password
修改强>
因此,如果您希望List<Object[]>
成为List<UserPojo>
,那么您需要遍历List<Object[]>
并手动分配UserPojo的字段。
for(Object[] obj : list) {
UserPojo userPojo = ...
userPojo.setUserId(obj[0]);
...
}
Obs:我不会那样使用它,但这取决于你。
答案 1 :(得分:0)
您的查询必须为List<Object[]>
子句中的所有字段返回select
。我认为只使用createQuery
中的实体名称应返回List<UserPojo>
:
"select user1 from UserPojo user1
where user1.userName=:userName and user1.password=:password"