Reputation: 24547
Today I tried Spring Data Neo4j, I finally got it working somehow...
I'm using:
Here's my config:
@Configuration
@EnableNeo4jRepositories(includeFilters=@Filter(value=GraphRepository.class, type=FilterType.ASSIGNABLE_TYPE))
public class Neo4jConfig extends Neo4jConfiguration {
public Neo4jConfig() {
setBasePackage("my.base.package");
}
@Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("/tmp/neo4j");
}
}
My Domain Class:
@NodeEntity
@QueryEntity
public class User implements Persistable<Long> {
@GraphId private Long id;
public Long getId() { return id; }
@NotNull @NotBlank @Email
@Indexed(unique=true)
private String email;
public String getEmail() { return email; }
void setEmail(String email) { this.email = email; }
@Override
public boolean isNew() {
return id==null;
}
@Override
public int hashCode() {
return id == null ? System.identityHashCode(this) : id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
And my Repository:
interface UserRepository extends GraphRepository<User>, CypherDslRepository<User> {}
I can successfully create a User in DB and afterwards retrieve it via:
User u = repo.query(
start(allNodes("user"))
.where(toBooleanExpression(QUser.user.email.eq("[email protected]")))
.returns(node("user")), new HashMap<String, Object>())
.singleOrNull();
BUT: if I now call my create code a second time, it won't throw an exception because of @Indexed(unique=true) String email
, it just overrides the the object in the DB.
AND: if I try to create a second User
with a different email value, the old user get's overridden.
The create code is just as simple as:
User u = new User();
u.setEmail("[email protected]");
repo.save(u);
I also tried to use a standalone version of Neo4j instead of the embedded one, with exactly the same result. In the webadmin view I can see, that it created some Indexes:
Node Indexes: Relationship Indexes:
User {"type":"exact"} __rel_types__ {"type":"exact"}
lucene lucene
The debug output also tells me that Spring creates an index:
2014-03-12 21:00:34,176 DEBUG o.s.data.neo4j.support.schema.SchemaIndexProvider: 35 - CREATE CONSTRAINT ON (n:`User`) ASSERT n.`email` IS UNIQUE
2014-03-12 21:00:34,177 DEBUG o.s.data.neo4j.support.query.CypherQueryEngine: 63 - Executing cypher query: CREATE CONSTRAINT ON (n:`User`) ASSERT n.`email` IS UNIQUE params {}
Some more debug output:
curl -v http://localhost:7474/db/data/index/node
{
"User" : {
"template" : "http://localhost:7474/db/data/index/node/User/{key}/{value}",
"provider" : "lucene",
"type" : "exact"
}
curl -v http://localhost:7474/db/data/schema/index
[ {
"property_keys" : [ "email" ],
"label" : "User"
} ]
curl -v http://localhost:7474/db/data/schema/constraint
[ {
"property_keys" : [ "email" ],
"label" : "User",
"type" : "UNIQUENESS"
} ]
I really can't imagine what I am doing wrong here...
Please help me!
UPDATE #1:
From what I've seen in AbstractGraphRepository.save
it uses Neo4jTemplate.save
which says:
Stores the given entity in the graph, if the entity is already attached to the graph, the node is updated, otherwise a new node is created.
So I assume that it always "thinks" that my entity is already attached. But why?
UPDATE #2:
If I go to the webadmin and do simply twice:
CREATE (n:User {email:'[email protected]'})
I get an error. So there must be something wrong with my Java code or SDN...
UPDATE #3:
Spring Data Neo4j's save
Method does something like GET or CREATE:
User u1 = new User();
u1.setEmail("[email protected]");
repo.save(u1); // creates node with id=0
User u2 = new User();
u2.setEmail("[email protected]");
repo.save(u2); // creates node with id=1
User u3 = new User();
u3.setEmail("[email protected]");
repo.save(u3); // updates and returns node with id=0
How can I fix this behavior? I want an exception.
UPDATE #4:
Seems like I was looking for that: http://docs.neo4j.org/chunked/stable/rest-api-unique-indexes.html#rest-api-create-a-unique-node-or-return-fail-create
Map<String, Object> prop1 = new HashMap<String, Object>();
prop1.put("email", "[email protected]");
neo4jTemplate.createNodeAs(User.class, prop1);
Map<String, Object> prop2 = new HashMap<String, Object>();
prop2.put("email", "[email protected]");
neo4jTemplate.createNodeAs(User.class, prop2);
This way it works as expected, at least I get an exception:
org.neo4j.rest.graphdb.RestResultException: Node 7 already exists with label User and property "email"=[[email protected]]
But now I can't figure out how to integrate this with the Spring Data Repository...
Upvotes: 4
Views: 2577
Reputation: 6400
If you are using SDN 3.2.0+ use the failOnDuplicate attribute:
@Indexed(unique = true, failOnDuplicate = true)
Upvotes: 2