【发布时间】:2015-03-05 14:02:56
【问题描述】:
我正在尝试使用 JSF 应用程序重置密码,但 userTransaction 不起作用。我将所有正确的值分配给实体,然后执行 utx.commit() 但在数据库中没有任何改变。显示“密码已重置”消息并且没有错误发生 你能帮助我吗?这是代码:
package it.polimi.meteocal.business.control;
import it.polimi.meteocal.business.beans.SendEmailBean;
import it.polimi.meteocal.business.entity.User;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
@ManagedBean
@RequestScoped
public class AccessValidation {
private String password;
private String confpassword;
private String username4email;
private String message;
private String email;
private String username;
@PersistenceContext
EntityManager em;
@EJB
private CheckFields cf;
@Resource
UserTransaction utx;
public void passwordReset() {
Query query;
User user;
if (!cf.checkPassword(password, confpassword)) {
message = "Passwords don't match";
} else if (confpassword.length() < 6) {
message = "Password should be at least 6 characters";
} else {
try {
query = em.createQuery("select u from User u where u.username=:um");
query.setParameter("um", username);
user = (User) query.getResultList().get(0);
utx.begin();
user.setPassword(password);
utx.commit();
message = "Password has been reset!";
} catch (Exception e) {
e.printStackTrace();
try {
utx.rollback();
} catch (IllegalStateException | SecurityException | SystemException exception) {
}
}
}
}
【问题讨论】:
-
将此语句
utx.begin();设为唯一try...catch块中的第一条语句。问题是,Query(连同User)实例位于事务边界之外——使其成为适当的事务单元。附带说明:您已经在使用注入点所暗示的 EJB(@EJB)。因此,为什么不简单地将业务逻辑迁移到它自己的位置(在 EJB 中)并使用容器管理的事务而不是手动使用这些 bean 管理的事务(除非它们显然不是绝对必要的)。
标签: jsf jpa transactions managed-bean