Hibernate version:2.1.8
Suppose I have a 1:n relationship between the classes A and B and there is a bidirectional association between these classes.
I use the following mapping:
Code:
<class name="A" table="TBL_A">
...
<bag name="Bs" lazy="true" inverse="true" cascade="none">
<key column="A_ID"/>
<one-to-many class="B"/>
</bag>
</class>
Code:
<class name="B" table="TBL_B">
...
<many-to-one name="a" class="A" cascade="none" column="A_ID" not-null="true"/>
</class>
I follow the session-per-request-with-detached-objects approach.
In the first request, I use a Session to retrieve an objectA (instance of class A). The collection of Bs that belong to objectA is initialized as well. Then this Session is closed.
Then I want to create a new instance of B:
Code:
B newB = new B();
newB.setA(objectA);
objectA.getBs().add(B);
I then want to issue a new request which calls a method to store the newB object.
Questions:
1. What should I pass to this method? What is good practice?
a) Both objectA and newB
b) Only newB
c) Only objectA and use a cascase like "all-delete-orphan"
2. Is the following code wrong? I agree that it's strange to get objectA by calling session.get() instead of passing it as an argument to this method or by calling b.getA(). But is it correct that this code prints out the previous size of the collection? Or should Hibernate have detected that the collection of Bs was changed by the session.saveOrUpdate(newB)?
Code:
public void storeB(B newB, Long idOfObjectA) {
session = sessionFactory.openSession();
Transaction tx = getCurrentSession().beginTransaction();
session.saveOrUpdate(newB);
// THE FOLLOWING DOES NOT WORK - IT WILL PRINT THE OLD SIZE!
A myA = session.get(A.class, idOfObjectA);
log.info(myA.getBs().size());
tx.commit();
session.close();
}