简体   繁体   中英

How to check if email already exists in DB - JPA, Java, JBoss

I am trying to check if the email the user enters already exists in the db. I have to methods (register and update) and one helper method in my 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;
    }

I don't know why but this code works perfect for the register method (whenever I enter an existing email address), but not for the update method, although they are very similar. Every time when I perform an user update, these SQL statements are performed in the following order (should be in reverse order):

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 ?

I already debugged the code and recognised that the update statement is executed on that line:

counter = (Long) this.entityManager
            .createQuery(
                    "SELECT COUNT(u.email) FROM User u WHERE u.email = :email")
            .setParameter("email", emailAddr).getSingleResult();

Any help would be greatly appreciated.

You've got a stale entity resulting of a transaction nightmate between JPA and your session bean. You've got to change your User entity lifecycle and make appropriate changes on your JPA transaction management.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM