Hibernate version:
Hibernate 3.1.1
Hibernate Annotations 3.1 beta8
I have defined 2 classes using annotations as follows. Note that the contactNumbers member is eager fetched.
Code:
@Entity
public class ContactNumber
{
@NotNull
String number;
String description;
}
@Entity
public class Person
{
...
@OneToMany(fetch = FetchType.EAGER)
@Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
@JoinTable(name = "person_contactnumber", joinColumns = @JoinColumn(name = "person_id"), inverseJoinColumns = @JoinColumn(name = "contactNumber_id"))
private List<ContactNumber> contactNumbers = new ArrayList<ContactNumber>();
...
}
I input the following test data into the database. Note that i enter 2 contactNumbers for the Person object created.
Code:
Person person = new Person();
List<ContactNumber> list= new ArrayList<ContactNumber>(2);
ContactNumber number = new ContactNumber();
number.setNumber("9111111");
number.setDescription("Work");
list.add(number);
number= new ContactNumber();
number.setNumber("1234567");
number.setDescription("Test");
list.add(number);
person.setContactNumbers(list);
session.save(person);
So the database now has 1 Person entry and 2 ContactNumbers for that Person.
And then when I use Criteria to query all the Persons in the database
Code:
session.createCriteria(Person.class).list();
the list contains 2 items referring to the same Person object I created (expected is that there would just be 1 Person in the list). I don't understand why the list would contain 2 items when the database only has 1 Person stored in it.
During my investigations, I found the following scenarios.
1. When the contactNumbers member of the Person class is NOT eager fetched, the list returns the correct number of Person instances. (As expected)
2. When the contactNumbers member of the Person class is eager fetched, the list returns multiple number of Persons based on the number of ContactNumbers associated to it. This probably explains why I get 2 Person items in the list since there are 2 contactNumbers created for that Person.
I don't understand why scenario 2 behaves this way. The number of Persons in the list generated by Criteria depends on the number of the eager fetched ContactNumbers. Can someone explain this behavior? Or is this a bug?
Thanks!