Search code examples
javahibernatejpaormhibernate-mapping

How to query by custom object entity property with JPA and Hibernate


Writing a DAO method to retrieve appUsers by email where email is of class EmailAddress. Been searching around for how to do this to no avail. Is there a way to retrieve records based off of the value of a custom object? This seems to work when I have a property that is of type String or int but how do I get records matching my EmailAddress object?

Tried the following but not working:

public List<AppUser> findByEmail(EmailAddress email) {
    log.debug("finding " + getTable() + " instance by example");

    AppUser appUser = new AppUser();
    appUser.setEmail(email);

    try {
        List<AppUser> results = this.sessionFactory.getCurrentSession()
                .createCriteria(AppUser.class)
                .add(Example.create(appUser)).list();
        log.debug("find by example successful, result size: "
                + results.size());
        return results;
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        throw re;
    }
}

Here's are the pertinent parts of my AppUser class

@Entity
@Table(name="AppUser")
public class AppUser extends BaseEntity {
    ...

    @Column(name="Email")
    private EmailAddress email;

    ...

    /**
     * Gets this AppUser's associated email
     * 
     * @return this AppUser's associated email
     */
    public EmailAddress getEmail() {
        return this.email;
    }

    /**
     * Sets this AppUser's associated email
     * 
     * @param email this AppUser's associated email
     */
    public void setEmail(EmailAddress email) {
        this.email = email;
    }   
}

And here is my EmailAddress class

  public class EmailAddress implements Serializable {
    private static final long serialVersionUID = -6999956021169014445L;
    private static final String AT_DELIMTER = "@";
    private String emailAddress;

    public EmailAddress() {}

    public EmailAddress(String emailAddress) {
        setEmailAddress(emailAddress);
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) throws IllegalArgumentException {
        if (StringUtils.isEmpty(emailAddress))
            throw new IllegalArgumentException("Parameter emailAddress cannot be blank.");
        else if (!EmailValidator.getInstance(true).isValid(emailAddress))
            throw new IllegalArgumentException("The email address " +  emailAddress + " is not valid.");

        this.emailAddress = emailAddress;
    }

    public String getUser() {
        return this.emailAddress.substring(0, this.emailAddress.indexOf(AT_DELIMTER));
    }

    public String getDomain() {
        return this.emailAddress.substring(this.emailAddress.indexOf(AT_DELIMTER) + 1);
    }

    public String toString() {
        return emailAddress;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((emailAddress == null) ? 0 : emailAddress.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EmailAddress other = (EmailAddress) obj;
        if (emailAddress == null) {
            if (other.emailAddress != null)
                return false;
        } else if (!emailAddress.equals(other.emailAddress))
            return false;
        return true;
    }
}

Thanks!


Solution

  • Change you query to:

    List results = this.sessionFactory.getCurrentSession()
        .createQuery("select au from AppUser au where au.email = :email")
        .setParameter("email", email)
        .list();
    

    You need to implement a Hibernate custom UserType to transform the DB strings to EmailAddress upon loading.

    Use the ImmutableType from the hibernate-types project as the base class of your custom Hibernate Type as it's much easier to implement it that way.