I'm having trouble with Hibernate 2 and lazy collections. To be more specific, Hibernate ignores the lazy attribute under certain circumstances.
Image two classes Company and Person. The Company holds a lazy reference to one or more Persons like:
Code:
public class Company {
// unimportant stuff here
private Set persons;
/**
* Returns all Persons of this Company. Only to be used by Hibernate.
*
* @hibernate.set lazy = "true"
* cascade = "all-delete-orphan"
* inverse = "true"
* order-by= "lastname"
*
* @hibernate.collection-key column = "companyId"
*
* @hibernate.collection-one-to-many class = "Person"
*
* @return a Set of Person instances.
*/
public Set getPersons_hbn() {
if ( persons instanceof RetraceableSet ) {
return (Set)((RetraceableSet)persons).getTarget();
} else {
return persons;
}
}
/**
* Sets the Persons of this Company. Only to be used by Hibernate.
*
* @param persons the Persons to set.
*/
public void setPersons_hbn(Set persons) {
this.persons = new RetraceableSet(this, "persons", persons);
}
}
public class Person {
// the code here actually doesn't matter
}
As you see, I'm wrapping Hibernate's collection type into one of my own when setting the property and unwrap it when reading it. I thought this would be completely transparent to Hibernate, because the property is accessed by the setter/getters.
However in this case, Hibernate ignores the lazy attribute. For some reason it obviously analyzes the bytecode of my class. Why is it doing this? When I change the implementation of the setter and getter to the very simple
Code:
public class Company {
public Set getPersons_hbn() {
return persons;
}
public void setPersons_hbn(Set persons) {
this.persons = persons;
}
}
everything works (well, the Hibernate part.). However, a slightest change in the implementation like
Code:
public class Company {
public Set getPersons_hbn() {
return persons;
}
public void setPersons_hbn(Set persons) {
System.out.println("Hello world.");
this.persons = persons;
}
}
causes it to ignore the lazy attribute again. Why is Hibernate doing this? And how can I stop it from doing so?
Hibernate version:
Hibernate 2.1.7
Mapping documents:
Generated from xdoclet, see Javadoc above.
Code between sessionFactory.openSession() and session.close():
Nothing more then session.createQuery(...).list();
Called inside a Spring HibernateTemplate.