I have a JPA entity with a manyToMany relationship defined. If I set the fetch type to eager for the collection or if I keep it lazy and make a call to get the collection, the collection populates just fine.
The problem is I want to force the population of this collection using a join in my query, but whenever I do that, I get an error like:
javax.persistence.NonUniqueResultException: result returns 4 elements
I'm not sure why this is happening. The 4 elements is based off the size of the collection, but why it's not forcing it to be loaded into collection has me stumped. I'm a newb so I'm sure it's something stupid I'm missing.
Posting some relevant code below:
Code:
@Entity
@Table(name = "Attribute")
@NamedQueries({
@NamedQuery(name = "Attribute.findByAttributeID", query = "SELECT a FROM Attribute a left join fetch a.attributeValues WHERE a.attributeID = :attributeID order by a.attributeID",
hints = {
@QueryHint(name = "org.hibernate.flushMode", value = "manual"),
@QueryHint(name = "org.hibernate.readOnly", value = "true")
})
})
public class Attribute implements Serializable {
//...
@JoinTable(name = "AttributeAttributeValue",
joinColumns = {@JoinColumn(name = "attributeID", referencedColumnName = "attributeID")},
inverseJoinColumns = {@JoinColumn(name = "attributeValueID", referencedColumnName = "attributeValueID")})
@ManyToMany
private Collection<AttributeValue> attributeValues;
//get/setter
}
public class AttributeValue implements Serializable {
@ManyToMany(mappedBy = "attributeValues")
private Collection<Attribute> attributes;
}
//in a test case:
Attribute a = (Attribute) em.createNamedQuery("Attribute.findByAttributeID").setParameter("attributeID", 1424).getSingleResult();