我正在使用Hibernate + JSF + PrimeFaces。现在我想更新admin的密码,但我总是得到错误对话框。我无法弄清楚我的代码中有什么问题。希望有人建议我。
loginBean(SessionScoped)
public class loginBean {
private Users username;
private UsersDao userdao;
/** Creates a new instance of loginBean */
public loginBean() {
userdao = new UsersDao();
username = new Users();
}
public Users getUsername() {
return username;
}
public void setUsername(Users username) {
this.username = username;
}
public void updateUser(){
String msg;
if(userdao.updateUser(username)){
msg = "Updated Successfully!";
}else{
msg = "Error. Please check again!";
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(msg, message);
}
}
UserDAO.java
public class UsersDao {
public boolean updateUser(Users user){
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try{
session.beginTransaction();
session.save(user);
session.beginTransaction().commit();
flag = true;
}catch(Exception e){
flag = false;
session.beginTransaction().rollback();
}
return flag;
}
}
XHTML
<p:growl id="growl" showDetail="true" life="3000" />
<h:form id="tab">
<h:outputLabel>Password</h:outputLabel>
<h:inputSecret value="#{loginBean.username.password}" />
<p:commandButton id="loginButton" value="Login" update=":growl" ajax="false" action="#{loginBean.updateUser}"/>
</h:form>
答案 0 :(得分:1)
您实际上正在对Session
执行save
操作,而不是update
,这就是为什么您有违反PRIMARY KEY 例外。您告诉Hibernate添加具有相同凭据的新用户,该用户受数据库约束。
此外,与具体问题无关,您应该将Users
班级名称更改为User
,因为它指的是具体用户。