@Elementcollection Java persistence (hibernate) causes duplicate instances to be loaded
•
Java
When @ elementcollection is used, multiple instances of all objects being loaded are loaded More specifically, it is loading an instance for each element in collectionofstrings
For example, a database with a single instance of MyClass is similar to collectofstrings Size() = = 4, the call to load all MyClass values will return a list of size 4 (all the same objects), instead of only 1 object
Is there a clean and simple way to solve this or expected behavior?
// 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();
Thank you, heavye
Edit: add findbycriteria call
Solution
I don't know if this is an error or legal behavior, but it can be done by applying distinct_ ROOT_ Entity result variable to fix:
protected List<T> findByCriteria(Session session,Criterion... criterion) {
Criteria crit = session.createCriteria(getPersistentClass());
for (Criterion c : criterion) {
crit.add(c);
}
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return crit.list();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
