Announcement Announcement Module
Collapse
No announcement yet.
Neo4j: Inheritence - get correct child (type) Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Neo4j: Inheritence - get correct child (type)

    Hi,

    i am using Spring Data Neo4j, Snapshot.

    I have two entities, where one is the motherclass:

    @NodeEntity
    ClassA {...}

    @NodeEntity
    ClassB extends ClassA {...}

    When retrieving an entity, i am using neoTemplate.findOne(id, ClassA.class). Retrieved object is always of type ClassA. How do i get the object to be of type ClassB, if the object is of that kind? You see, i am searching for a kind of factory.

    Greetz,
    Markus

  • #2
    Markus,

    You can do both casting and conversion, or projection(http://static.springsource.org/sprin...del:projection) depending on the situation:

    Code:
    @NodeEntity
    class Foo {
        @GraphId
        Long id;
    }
    
    @NodeEntity
    class Bar extends Foo {
        int baz;
    
        Bar() {
        }
    
        Bar(int baz) {
            this.baz = baz;
        }
    }
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class InheritanceTests {
        @Configuration
        @EnableNeo4jRepositories
        static class TestConfig extends Neo4jConfiguration {
            @Bean
            GraphDatabaseService graphDatabaseService() {
                return new ImpermanentGraphDatabase();
            }
        }
    
        @Autowired
        Neo4jTemplate template;
    
        long id;
    
        @Before
        public void before() {
            Transaction transaction = template.getGraphDatabaseService().beginTx();
    
            id = template.save(new Bar(42)).id;
    
            transaction.success();
            transaction.finish();
        }
    
        @Test
        public void shouldFindSubclass() throws Exception {
            Bar bar = template.findOne(id, Bar.class);
            assertThat(bar.baz, is(42));
    
            Foo foo = template.findOne(id, Foo.class);
            assertThat(((Bar) foo).baz, is(42));
    
            bar = template.convert(foo, Bar.class);
            assertThat(bar.baz, is(42));
        }
    }

    Comment


    • #3
      Scary.. and great ;-) Thank you!

      Comment

      Working...
      X