@ElementCollection Java Persistence (Hibernate) Causes Loading of Duplicate Instances

Viewed 8431

When using @ElementCollection, load all is loading multiple instances of an object. More specifically, it is loading one instance for each element in the collectionOfStrings.

For example, a database with a single instance of MyClass with collectionOfStrings.size() == 4, the call to load all MyClass values will return a List of size 4 (all the same object) instead of just 1 object.

Is there a clean and simple way to resolve this or is the behaviour expected?

// Parent class is a @MappedSuperclass which may or may not be relevant to the issue
@Entity
public class MyClass extends ParentClass {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ElementCollection(fetch=FetchType.EAGER)
    @IndexColumn(name="indexColumn")
    private List<String> collectionOfStrings;

    // other instance variables, constructors, getters, setters, toString, hashcode and equals
}

public class MyClassDAO_Hibernate extends GenericHibernateDAO<MyClass, Long> implements MyClassDAO {

    @Override
    public List<MyClass> loadAll() {
        List<MyClass> entityList = null;
        Session session = getSession();
        Transaction trans = session.beginTransaction();
        entityList = findByCriteria(session);
        trans.commit();
        return entityList;
    }

}

protected List<T> findByCriteria(Session session, Criterion... criterion) {
    Criteria crit = session.createCriteria(getPersistentClass());
    for (Criterion c : criterion) {
        crit.add(c);
    }
    return crit.list();
}

MyClassDAO myClassDAO = new MyClassDAO_Hibernate(); // in reality, implementation type is determined with a Factory
...
List<MyClass> myClassInstances = myClassDAO.loadAll();

Thanks, HeavyE

Edit: added findByCriteria call.

3 Answers
Related