我正在尝试检查用户输入的电子邮件是否已存在于数据库中。 我必须在UserBean.java中使用方法(注册和更新)和一个帮助方法:
public String register() {
if (emailAlreadyExists(this.user.getEmail())) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("This e-Mail is already in use."));
} else {
this.conversation.end();
try {
if (this.id == null) {
this.entityManager.persist(this.user);
return "thanks.xhtml";
} else {
this.entityManager.merge(this.user);
return "thanks.xhtml";
}
} catch (EJBTransactionRolledbackException e) {
Throwable t = e.getCause();
while ((t != null)
&& !(t instanceof ConstraintViolationException)) {
t = t.getCause();
}
if (t instanceof ConstraintViolationException) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(e.getMessage()));
return null;
}
}
}
return null;
}
public String update() {
if (emailAlreadyExists(this.user.getEmail())) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("This e-Mail is already in use."));
} else {
this.conversation.end();
try {
if (this.id == null) {
this.entityManager.persist(this.user);
return "search?faces-redirect=true";
} else {
this.entityManager.merge(this.user);
return "view?faces-redirect=true&id=" + this.user.getId();
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(e.getMessage()));
return null;
}
}
return null;
}
public boolean emailAlreadyExists(String emailAddr) {
long counter = 0;
counter = (Long) this.entityManager
.createQuery(
"SELECT COUNT(u.email) FROM User u WHERE u.email = :email")
.setParameter("email", emailAddr).getSingleResult();
if (counter > 0) {
return true;
}
return false;
}
我不知道为什么,但这段代码适用于注册方法(无论何时我输入现有的电子邮件地址),但不适用于更新方法,尽管它们非常相似。 每次执行用户更新时,这些SQL语句都按以下顺序执行(应按相反顺序):
22:44:20,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate: update User set country=?, email=?, firstName=?, lastName=?, password=?, phone=?, postalCode=? where id=?
22:44:20,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate: select count(user0_.email) as col_0_0_ from User user0_ where user0_.email=? limit ?
我已经调试了代码,并认识到在该行上执行了update语句:
counter = (Long) this.entityManager
.createQuery(
"SELECT COUNT(u.email) FROM User u WHERE u.email = :email")
.setParameter("email", emailAddr).getSingleResult();
非常感谢任何帮助。
答案 0 :(得分:1)
您有一个陈旧的实体,导致JPA和您的会话bean之间的交易夜友。您必须更改用户实体生命周期并对JPA事务管理进行适当的更改。