Search code examples
javahibernatejpamany-to-manypersistence

Make Hibernate treat detached objects as same instance


I have a many to many relationship between two tables. I first fill parent objects with child objects and vice versa. When I stumble upon a new, before unseen child object, I add it to a hash map, and connect the parent and child with their collections as needed. Every iteration I check if the child already exists in the map, and if It doesn't, I create it and add it to the map, and then of course connect the child and parent with their collections. However, at the end, when I persist all of the parents, the children get persisted as many times it is referenced by the parent objects, I get duplicates in child table. How could I tell Hibernate that these duplicates are one and the same object?

One solution would be to persist every new, before unseen child, so I could get Its id and based on that Hibernate would now that this is the same object. But can this be achieved without in between persist commands, that is, to call persist (on parent objects) only at the end, when all mappings are set?


Solution

  • What I did is, instead of a map, use separate collections for the parent and child objects. After that I just persisted the parent object collection and that was It (because child object can't exist without a parent object, but parent can without child objects, otherwise I could also instead persist the child objects).

    So the problem with map was, that although you add a value to a specific keys collection values from another keys collection values, It does not reference the same object, i.e. It creates a new one for the other key collection, which is why in this case you get duplicates when persisting the key values (which are the parent objects).