Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does my "one-to-many" Hibernate attribute get method return an empty collection?
    primarykey
    data
    text
    <p>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.</p> <p>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 ( <em>[HibernateBeans.Pet@76838e, HibernateBeans.Pet@b71950]</em> ).</p> <p>Frustratingly (and incorrectly), my code below returns an empty collection when I pass in the exact same user that I successfully queried for:</p> <pre><code>public ArrayList&lt;Pet&gt; getPets(User user) { Set&lt;Pet&gt; 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; } </code></pre> <p><strong>EDIT</strong>: 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:</p> <p>Here are the relevant XML Hibernate mappings: </p> <p><strong>User.hbm.xml:</strong></p> <pre><code>&lt;set name="pets" inverse="true"&gt; &lt;key&gt; &lt;column name="UserID" not-null="true" /&gt; &lt;/key&gt; &lt;one-to-many class="HibernateBeans.Pet"/&gt; &lt;/set&gt; </code></pre> <p><strong>Pet.hbm.xml:</strong></p> <pre><code>&lt;many-to-one name="user" class="HibernateBeans.User" fetch="select"&gt; &lt;column name="UserID" not-null="true" /&gt; &lt;/many-to-one&gt; </code></pre> <p>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 <em>many</em> an occasion.</p> <p>Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload