我正在学习 Hibernate,并且在使用 hql 时遇到了困难。我希望我的函数检查数据库中是否存在用户名。private boolean userExists(Session session, String userName) { String hql = "select 1 from entity.User u where u.userName = :userName"; Query query = session.createQuery(hql); query.setParameter("userName", userName); return query.uniqueResult() != null; }上面的函数位于我的 UserControl 类中。这是我在 IntelliJ 中的项目布局:在我的 UserControl 类中,我已经导入了我的 User 类import entity.User,但我仍然不能User在 HQL 中使用裸类名而不是entity.User没有得到以下错误。java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [select 1 from User u where u.userName = :userName]我对类似问题的搜索让我找到了这个答案和页面上的其他人,这表明我的实体类的命名存在一些错误,尽管我基于答案的实验没有奏效。entity.User如果我像上面那样屈服并使用,那么我会收到此错误:java.lang.IllegalArgumentException: Could not locate named parameter [userName], expecting one of []这是我的实体类:package entity;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name = "user_association", schema = "login_register_view")public class User { private int id; private String userName; private String password; private String color; private Integer pocketCount; private Double weight; @Id @Column(name= "id", nullable = false) public int getId(){ return id; } public void setId(int id){ this.id = id;} @Column(name = "user_name") public String getUserName(){ return userName; } public void setUserName(String userName){ this.userName = userName; } @Column(name = "password") public String getPassword(){ return password; } public void setPassword(String password){ this.password = password; } @Column(name = "color") public String getColor(){ return color; } public void setColor(String color){ this.color = color; } @Column(name = "pocket_count") public Integer getPocketCount(){ return pocketCount; } public void setPocketCount(Integer pocketCount){ this.pocketCount = pocketCount; }}
1 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
我发现发生这种情况的原因是因为我没有在我的 hibernate.cfg.xml 中映射实体。在里面<session-factory> </session-factory>
我需要写:
<mapping class="entity.User"/>
添加回答
举报
0/150
提交
取消