您好我使用spring mvc 3和hibernate 4开发了一个Web应用程序。我正在为所有配置使用注释。
当我尝试选择实体时,我收到错误:
DaoException: unexpected token: MEMBER near line 1, column 37 [from clanwar.model.ClanMember where MEMBER = :member]
at clanwar.dao.impl.ClanMemberDao.findByPlayerId(ClanMemberDao.java:71)
如果我使用.createSQLQuery()
hibernate执行查询,请返回Object[]
实体ClanMember
实例。
DAO中的方法:
@Repository
@Transactional
...
@Override
public ClanMember findByPlayerId(int id) throws DaoException {
ClanMember foundMember;
try {
foundMember = (ClanMember) getSession()
.createQuery("from ClanMember where MEMBER = :member")
.setParameter("member", id)
.uniqueResult();
} catch (Exception e) {
throw new DaoException(e.getMessage());
}
return foundMember;
}
...
实体:
@Entity
@Table(name = "CLAN_MEMBERS")
public class ClanMember implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "CLAN")
private Clan clan;
@Id
@ManyToOne
@JoinColumn(name = "MEMBER")
private Player member;
@ManyToOne
@JoinColumn(name = "ROLE")
private ClanRole role;
public ClanMember() {}
// Setters and getters
}
表CLAN_MEMBERS:
+--------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| CLAN | int(11) | NO | PRI | NULL | |
| MEMBER | int(11) | NO | PRI | NULL | |
| ROLE | int(11) | NO | | 1 | |
+--------+---------+------+-----+---------+-------+
我做错了什么? 提前谢谢。
答案 0 :(得分:0)
您的查询应如下所示:
from ClanMember where member = :member
因此,获取成员的代码应如下所示:
foundMember = (ClanMember) getSession()
.createQuery("from ClanMember where member = :member")
.setParameter("member", id)
.uniqueResult();
另请注意,您传递的id
应该是Player
类的实例。
答案 1 :(得分:0)
member
是HQL中的保留字。通过添加表别名来逃避它。
此外,由于member
的类型为Player
,因此当您的where clause
包含member
时,您需要提供Player
类型的参数。或者,如果您想提供您正在执行的ID,则需要明确搜索id
:
所以:
foundMember = (ClanMember) getSession()
.createQuery("from ClanMember c where c.member = :member")
.setParameter("member", someInstanceOfPlayer);
.uniqueResult();
或
foundMember = (ClanMember) getSession()
.createQuery("from ClanMember c where c.member = :member")
.setParameter("member", idOfAPlayer);
.uniqueResult();