使用@ElementCollection時,加載全部加載對象的多個實例。更具體地說,它爲collectionOfStrings中的每個元素加載一個實例。@ElementCollection Java持久性(Hibernate)導致加載重複實例
例如,一個MyClass的實例與collectionOfStrings.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
編輯:添加findByCriteria電話。
你如何加載實體? – axtavt
axtavt,我在我最初忽略的findByCriteria方法中添加了。 – HeavyE