Hi everybody,
I've faced with some interesting bug, when querying for an object
in two different ways affects the one-to-many association.
I have an Order entity with one-to-many relationship with Ticket entity.
Code:
@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, mappedBy = "parentOrder")
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public Collection<Ticket> getTickets()
{
return tickets;
}
Using the following method to find an Order by primary key:
Code:
@Override
public Order findById(Serializable id)
{
return jpaTemplate.find(Order.class, id);
}
results in fetching the Order object with 2(!) tickets in tickets collection while there is only one(!) in database !
I was playing a bit and changed the above method to query for Order entity by id differently:
Code:
@Override
public Order findById(Serializable id)
{
List results = jpaTemplate.find("select o from Order o where o.id = ?1", id);
return results.size() > 0 ? (Order) results.get(0) : null;
}
That did a trick, now everything is fine. I'm getting 1 ticket object in tickets collection.
Can anybody tell what was that ? How could duplicates items appear in collection ?