These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Updating bidirectional associations
PostPosted: Tue Jun 28, 2005 11:11 am 
Newbie

Joined: Tue Jun 28, 2005 11:02 am
Posts: 2
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();
}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.