问题
I need help, I am getting the aforementioned exception. Where am I going wrong? In the mapping from class to table, I have used the following:
private String userId;
private String password;
Below is the class where I write my query.
public class LoginManager extends HibernateUtil {
private String loginId;
public String checkCredentials(String userId, String password) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
loginId = (String) session.createQuery("select user_id from com.project.model.Login where user_id=:userId and password=:password")
.setParameter("userId",userId)
.setParameter("password", password)
.list().toString();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return loginId;
}
}
Entity
@Entity
@Table(name = "Login")
public class Login implements Serializable {
private static final long serialVersionUID = 2L;
private String userId;
private String password;
@Id
@Column(name = "user_id")
public String getUserId() {
return userId;
}
public void setUser_id(String userId) {
this.userId = userId;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
回答1:
The problem is that Hibernate cannot find your setter for the field userId. You have defined it like this:
public void setUser_id(String userId) {
this.userId = userId;
}
It should be:
public void setUserId(String userId) {
this.userId = userId;
}
回答2:
Hibernate map your database by your variable name. So you have;
userId;
but in your query you have
user_id
You need to use userId
not user_id
.
And exception clearly says you provided the wrong parameter.
回答3:
Check if it is typo error
loginId = (String) session.createQuery("select user_id from com.project.model.Login where user_id=:userId and password=:password") .**setParameter("userId",userId)**.setParameter("password", password).list().toString();
loginId = (String) session.createQuery("select user_id from com.project.model.Login where user_id=:userId and password=:password") .**setParameter("user_id",userId)**.setParameter("password", password).list().toString();
来源:https://stackoverflow.com/questions/18680813/org-hibernate-queryparameterexception-could-not-locate-named-parameter-userid