[Neo4j] hello people

Jim Webber jim at neotechnology.com
Mon Dec 13 08:45:23 CET 2010


Hi Jose,

[warning: I wrote this code in my email client, it may not even compile, but it should give you the right idea]

Rather than use inheritance to build your domain model, composition is preferred. So:

class Person {
  Node node;

  public Person(String name, int age, Node dbNode) {
    node = dbNode;
    node.setProperty("name", name);
    node.setProperty("age", age);
  }

  // Other methods elided for brevity

}

To use this, you'll have to create a transaction and a node in the DB:

Transaction tx = db.beginTx();
try {
  Node me = db.createNode();
  Person me = new Person("Jim", 36, me);
  tx.success();
} finally {
  tx.finish();
}

If you want to, for example, create some friends, add such a method to your domain model:

public void friendsWith(Person p) {
  this.node.createRelationshipTo(p, FRIENDS_WITH);
}

Of course the FRIENDS_WITH relationship needs to be defined:

public class FriendsWith implements RelationshipType {
    private FriendsWith(){}
    
    public static final FriendsWith FRIENDS_WITH = new FriendsWith(); 
    
    public String name() {
        return "works-for";
    }
}

And remember to create the relationship within a transactional scope:

Transaction tx = db.beginTx();
try {
 me.friendsWith(you); // me and you are of type Person
  tx.success();
} finally {
  tx.finish();
}


Hope that helps.

Jim


More information about the User mailing list