It's my first post here, so hello again
Right to the point, I have been fighting all day against a quite strange behaviour. I know it's my fault but I really cannot find where I make my mistake.
I have two tables (Postgres DB using Hibernate 4.1.7 as ORM), one called player and one called tie. A tie is established between two players obviously. It's important to track who sent the tie and who accepted it, so I ended up with two tables like this (very simplified!):
The requesting_player and target player are obviously referring to the matching entity in Player table. Status is just accepted/not accepted and is not interesting at the moment. The tie table has two foreign keys pointing to player, one for the requesting player and one for the target player (both with cascade for delete and update).
I modelled my classes as follows:
Obviously the "Tie" class has two ManyToOne reference as well:
Now what is odd is this: the following code works perfectly:
while the following code:
return false. It returns true if I change the dbsession.load with dbsession.get (which does make sense somehow, since get gets the current loaded object without issuing a new query as far as I understand but still is odd that it works right in the first snippet) but in that case there is some sort of strange behaviour: Hibernate deletes ALL ties belonging to the player on the commit:
Hibernate: delete from tie where requesting_player=?
which does not make much sense... if I inspect the currentPlayer object after the "remove" he still has all his other ties. I checked my mappings and both seems exactly alike. I really cannot understand what's wrong there. Hope someone sees something I am missing. Probably the class layout is not the best... it seems there is some problem with two collection referring to the same details table.
Thanks in advance!
Edit: Obviously tieId in the two snippets refer to the primary key "id" of the tie and they are ties belonging to the right collection.
Joined: Oct 24, 2012
Ok it was NOT odd, I just was not seeing the things right. What confused me was one of the two collections working properly. My mistake was to make the "one" side of a one to many relationship the owning side. I fixed everything by just inverting the relationship, hence:
In the Player class and mapping as owning side the Tie class:
This way everything works fine with a small change:
(so I have to delete the tie instead of simply removing it from the collection)
Yup if you have a bi directional relationship the @OneToMany is always the inverse side, which makes sense. In certain types of relationships you can set orphan-removal = true. This will allow you to simply remove it from the collection and it will automatically be deleted. You want to make sure that you have that 'special type' of relationship though before setting that property. I described it in this thread: