I’ve setup a “one-to-many”/”many-to-one” bi-directional mapping relationship for a User class and a Pet class (for a pet store-themed academic web project). Each User owns collection of pets.
It seems the relationship is working fine, because when I execute a query to select the first User in my database in NetBeans’ HQL Query Browser, I see that the “Pets” attribute has 2 Java object ID’s listed, presumably the two pets I referenced via the foreign key ( [HibernateBeans.Pet@76838e, HibernateBeans.Pet@b71950] ).
Frustratingly (and incorrectly), my code below returns an empty collection when I pass in the exact same user that I successfully queried for:
public ArrayList<Pet> getPets(User user) {
Set<Pet> pets = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
pets = user.getPets();
for (Pet p : pets) System.out.println(p.getPetName());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return pets;
}
EDIT: As per Tahir’s suggestions, I’ve removed the annotations from my Java classes and am now strictly using POJO XML mapping (but the same problem persists). My source code below has been updated accordingly:
Here are the relevant XML Hibernate mappings:
User.hbm.xml:
<set name="pets" inverse="true">
<key>
<column name="UserID" not-null="true" />
</key>
<one-to-many class="HibernateBeans.Pet"/>
</set>
Pet.hbm.xml:
<many-to-one name="user" class="HibernateBeans.User" fetch="select">
<column name="UserID" not-null="true" />
</many-to-one>
Any help at all on this issue would be greatly appreciated. Although this is my first time posting a question, StackOverflow has saved my life on many an occasion.
Thanks in advance!
Are you using both the XML and annotations based mapping in the same project? I would recommend using a single method (in your case annotations).
Your XML version of mapping is not declaring the User.pets as eagerly loaded property. That could be the reason you are seeing an empty list.
EDIT:
As you are still getting the issue after switching over to only xml mappings, I suggest trying the following:
newkeywordlazy="false"in your mappingPoints 2 and 3 are just for giving you a lead in debugging. Given that you are not eagerly loading
pets, any attempt to calluser.getPets()after closing the original session should result in anorg.hibernate.LazyInitializationException.EDIT:
One more thing to check would be that you are not manually assigning a value to User.pets field. Hibernate supplies a custom implementation of collections to be able to provide the lazy initialization.