Enrico Morelli
Enrico Morelli

Reputation: 173

JPA: better way to check if an entity has an association

Which is the better way to check if an entity has attached association? I've a OneToOne association between Participant and Abstract entity and I want to know if a Participant has an abstract. For the moment I use the following code. Is there a better way?

public Long hasAbstract(String email) {
    Long absID;
    Participant p = find(email);
    try {
        return p.getAbstract_().getId();
    } catch (NullPointerException e){

    }
    return 0L;
}

Upvotes: 0

Views: 216

Answers (1)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

Avoid using the exception handling to facilitate logic where possible. Instead just check if the object is null:

    public boolean hasAbstract(String email) {

         Participant p = find(email);
         return p.getAbstract_() == null ? 0L : p.getAbstract_().getId();
    }     

Upvotes: 1

Related Questions