当使用@ElementCollection时,加载全部正在加载对象的多个实例.更具体地说,它正在为collectionOfStrings中的每个元素加载一个实例.
例如,具有单个实例MyClass的数据库与collectOfStrings.size()== 4,调用加载所有MyClass值将返回一个大小为4的列表(所有相同的对象),而不是只有1个对象.
// 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();
谢谢,
HeavyE
解决方法
我不知道这是否是一个错误或合法的行为,但可以通过应用DISTINCT_ROOT_ENTITY结果变量来修复:
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(); }