org.hibernate.QueryParameterException: could not locate named parameter [userId]

你说的曾经没有我的故事 提交于 2019-12-22 11:25:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!