views:

88

answers:

1

I solved my problem, but I just want to get a better understanding of how things are working.

I am looping through a collection, creating/initializing a new Product, adding a category it its collection (mapped m:m) and then saving and commiting the transaction.

for(Blah b : blahs)
{
  session = getcurrensession();

  Product p = new Product(1,2,3,4,5);



  Category c = Dao.GetById(b.categoryId);

  session.beginTransaction();

  p.getCategories().add(c);
  session.save(p);

  session.gettransaction.commit();
}

Now I was getting an error saying that another object with the same id is already being tracked, so there was a duplication error going on.

I figured it was the category object, and indeed that was the problem, so I did this:

Category c = null;
forloop
{

..

  if(c == null || c.getId() != b.categoryId)
         c = Dao.GetById(b.categoryId);

...

}

So now the category is not loaded unless it has a different id, and now my program worked fine.

This issue is, is there another way to do this?

Can I force Hibernate to stop tracking that object so I can just load it w/o worrying about these issues?

+1  A: 

well Dao.GetById(b.categoryId); should always return those Category object with passed id, how is it possible to get different Category objects? if you have two instances of session then there should not be a problem unless you are updating the same row in parallel from both sessions which would be a stale object issue.

scienty