I have found that if create the Parent object, save it, and call "getChildren()" the object returned is null. However, if I close the session, and open a new session, then getChildren() returns an empty collection.
I am wondering if the session rememberers that the parent has no children, so it returns null. When I close the session, it does not remember, so it queries, finds no results returns an empty set?
If this is the case I wonder what happens in this case:
I create a Parent in my session.
Then you could add children to the Parent I just created in your session.
Next, I call getChildren, and it returns null, not knowing that you updated it.
I just want to make sure that if I get a null I can safely assume there is no children currently in the parent.
I've included source for this example, as well as the requested data. Thanks for your input.
Hibernate version: 2.1
Mapping documents:
Code:
<class name="com.mobileresearch.kol.hibernate.Parent" table="parent" >
<id name="id" column="uid" type="long" unsaved-value="null">
<generator class="identity"/>
</id>
<set name="children" lazy="true">
<key column="parent_id"/>
<one-to-many class="com.mobileresearch.kol.hibernate.Child"/>
</set>
</class>
<class name="com.mobileresearch.kol.hibernate.Child" table="child" >
<id name="id" column="uid" type="long" unsaved-value="null">
<generator class="identity"/>
</id>
<property name="name" type="string" />
<many-to-one name="parent" column="parent_id" class="com.mobileresearch.kol.hibernate.Parent" not-null="true" />
</class>
Here is java source:Code:
public static void main(String args[]) throws HibernateException {
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
Long parentId;
// make the parent, get the id.
{
Transaction tx = session.beginTransaction();
Parent p = new Parent();
session.save(p);
parentId = p.getId();
tx.commit();
}
// this is the variable part, uncomment these lines to make non-null
//session.close();
//session = sessionFactory.openSession();
// look up the parent, see if children set is null
{
Parent p = (Parent)session.get(Parent.class, parentId);
System.out.println( p.getChildren() );
}
session.close();
}
Database: MySQL 4.1.10a-ntThe generated SQL With Session being closed and re-opened:Code:
Hibernate: insert into parent values ( )
Hibernate: select parent0_.uid as uid0_ from parent parent0_ where parent0_.uid=?
Hibernate: select children0_.parent_id as parent_id__, children0_.uid as uid__, children0_.uid as uid0_, children0_.name as name0_, children0_.parent_id as parent_id0_ from child children0_ where children0_.parent_id=?
The generated SQL With same Session the whole time:Code:
Hibernate: insert into parent values ( )