org.hibernate.hql.ast.QuerySyntaxException: unexpected token: and near line 1, c

aoyiufuwa 2012-06-13 07:01:26
类方法:
public Users getAdminList(Users users) {
StringBuffer hqlQuery=new StringBuffer();//注意对比StringBuffer和String的区别
hqlQuery.append("from USERS u where ");
if(users.getUserID()!=null){
hqlQuery.append("and (u.userID=:userID)");
}else{//如果id不存在,才查询其他属性
if(users.getUserName()!=null){
hqlQuery.append("and (u.userName=:userName)");//加括号是为了方式忘记加空格和破坏优先级,例如
if(users.getPassword()!=null){//如果用户为null,那么就不必再查询密码了
hqlQuery.append("and (u.password=:password)");
}
}
}
String hql=hqlQuery.toString();
Object o=BaseHibernateDAO.selectHQLObject(hql,users);
if(o!=null){
return (Users)o;
}else{
return null;
}
}

运行时出错:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: and near line 1, column 20 [from USERS u where and (u.userName=:userName)and (u.password=:password)]


Users.hbm.xml文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class lazy="true" name="entity.Users" table="users">
<id name="userID" type="java.lang.Integer">
<column name="userID"/>
<generator class="native">

</generator>
</id>
<property generated="never" lazy="false" name="userName" type="java.lang.String">
<column length="20" name="userName" not-null="false"/>
</property>
<property generated="never" lazy="false" name="password" type="java.lang.String">
<column length="20" name="password" not-null="false"/>
</property>
</class>
</hibernate-mapping>
实体类是:Users.java
...全文
941 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dxy860812 2013-12-24
  • 打赏
  • 举报
回复
你语法就错了吧1楼正解if(users.getUserID()!=null){ hqlQuery.append("and (u.userID=:userID)"); }else{//如果id不存在,才查询其他属性 if(users.getUserName()!=null){ hqlQuery.append("and (u.userName=:userName)");//加括号是为了方式忘记加空格和破坏优先级,例如 if(users.getPassword()!=null){//如果用户为null,那么就不必再查询密码了 hqlQuery.append("and (u.password=:password)"); } } } 红色那句改成hqlQuery.append(" (u.userID=:userID)");你再试试
aoyiufuwa 2012-06-13
  • 打赏
  • 举报
回复
但是运行只提示:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: and near line 1, column 20 [from USERS u where and (u.userName=:userName)and (u.password=:password)]

这个错误,并没有from USERS u where and (u.userID=:userID)这句

brightyq 2012-06-13
  • 打赏
  • 举报
回复
错误信息已经指出来了。
hqlQuery.append("from USERS u where ");
if(users.getUserID()!=null){
hqlQuery.append("and (u.userID=:userID)");
}

两里句执行后的hql结果是这样: from USERS u where and (u.userID=:userID)
看出来没?"where" 后直接跟的一个"and"

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧