Announcement Announcement Module
Collapse
No announcement yet.
Bidirectional relationship not being set Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Bidirectional relationship not being set

    I have two classes in an m:n relationship, defined as:
    Code:
    public class Item {
    	@RelatedTo(type="MEMBERS", direction = Direction.INCOMING) 
    	Set<Layer> layers;
    }
    public class Layer {
    	@RelatedTo(type="MEMBERS") 
    	Set<Item> items;
    }
    My reading of the docs is that these connections will be automatically created by the bit-twiddling under the covers. So that when an Item is added to the items attribute of Layer, a corisponding relationship should be created from Item.layers back to the Layer the Item was added to. But this is not happening. The following test fails:

    Code:
    @Test
    @Transactional
    public void testTwoWayRelationshipCounts(){
    	Layer layer1 = repository.save(new Layer());
    	Layer layer2 = repository.save(new Layer());
    	Item item1 = template.save(new Item());
    	
    	layer1.addItem(item1);
    	layer2.addItem(item1);
    	repository.save(layer1);
    	repository.save(layer2);
    	template.save(item1);
    	
    	assertEquals(1, layer1.items.size());
    	assertEquals(1, layer2.items.size());
    	assertEquals(2, item1.layers.size()); // fails, as it is 0
    }
    Am I not understanding something? Or is this a bug?

    Thanks.

  • #2
    I would save the Item first. so put template.save(item1) before the two repository.save calls.

    I am thinking that the repo calls to save can't create the relationship on an item that isn't a node in the db yet.

    Actually, more of a problem is how is the item1 supposed to automatically have two objects added to its set magically. Who would call it based on your code. No one did. This is just Java that caused that, nothing about neo4j or Spring Data neo4j. Now if you do a find/query after you have saved your objects, then the item will have its layers.

    In say JPA, you have to make sure you set both sides in your code if you want it to work without querying the database to refresh the objects. I think that would be the same here.

    Hope that helps.

    Mark

    Comment


    • #3
      To your first point, about saveing item1, it is saved by the time it is added to the layers. So that's not relevent.

      As to your second point, about adding the relations, the Neo4j documentation very clearly states that it does in the AspectJ/bit-twiddled code. It would kind of have to do this too, as otherwise, there would be know way in code of handleing this, without bringing all of the contents of the relationship into memory, negating the lazy-loading stratagy. You couldn't do 'add to collection if not present'.

      Comment

      Working...
      X