Question

Lets assume the following situation: I have two entity classes Person and Comment.

//Person class
@Entity
public class Person extends AbstractBusinesObject{

@OneToMany(mappedby ="owner")
private List<Comment> comments;

//Comment class
@Entity
public class Comment extends AbstractBusinesObject{

@ManyToOne
private Person owner;

I would like to know which approach is better (performance, memory-efficiency) from the following two alternatives to determine whether a specific comment belongs to a specific person or not.

public boolean isUsersComment(Person p, Comment c){
    return p.getComments().contains(c);
}

or

public boolean isUsersComment(Person p, Comment c){
    CriteriaBuilder cb = getEntitymanager().getCriteriaBuilder();
    CriteriaQuery<Comment> cq = cb.createQuery(Comment.class);
    Root<Comment> root = cq.from(Comment.class);
    cq.select(root).where(cb.and(cb.equal(root, c), cb.isTrue(root.in(p.getComments())));
    try{
        getEntityManager().createQuery(cq).getSingleResult();
        return true;
    } catch (NoResultException ex){
        return false;
    } catch (NoUniqueResultException ex){
        throw new IllegalStateException(message);
    }
}

As far as i know criteria api generates a database query, while the first solution searches in a collection.

Thank you for your answer.

ps: I am new to Criteria API, so I also accept fixes/suggestions.

Edit

Ok, I have found out it was a stupid question; As I declared a bidirectional relationship, the solution is very simple:

return c.getOwner.equals(p);

Anyway, what is the approach in case of unidirectional relationship?

Was it helpful?

Solution

Depends if the original Collection is already loaded, no? If the Collection is loaded then its a straight contains() call, otherwise it likely would be the equivalent of what a query (Criteria or JPQL) would do.

If the Collection was large then I'd go through a query always (since I wouldn't want to load the whole collection). Otherwise I'd use Collection.contains

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top