1
此測試失敗,錯誤,我不明白爲什麼.. 我認爲UniqueNodeFactory
只有當它不存在時創建節點。 當然,我可以使用Cypher做同樣的事情,但我想了解這裏會發生什麼.. 有人可以解釋嗎? 我正在使用neo4j 2.3.1。ConstraintViolationException當使用UniqueNodeFactory創建節點
public class SimpleTest {
private GraphDatabaseService graphService;
@Before
public void setUp() throws Exception {
graphService = new TestGraphDatabaseFactory().newImpermanentDatabase();
graphService.execute("CREATE CONSTRAINT ON (user:User) ASSERT user.userId IS UNIQUE");
}
@After
public void tearDown() throws Exception {
graphService.shutdown();
}
public static UniqueFactory.UniqueNodeFactory createUserFactory(GraphDatabaseService graphDatabaseService) {
return new UniqueFactory.UniqueNodeFactory(graphDatabaseService, "User") {
@Override
protected void initialize(Node created, Map<String, Object> properties) {
created.addLabel(DynamicLabel.label("User"));
created.setProperty("userId", properties.get("userId"));
}
};
}
@Test
public void testCreateUser() throws Exception {
try (Transaction tx = graphService.beginTx()) {
Node node = graphService.createNode(DynamicLabel.label("User"));
node.setProperty("userId", 100L);
tx.success();
}
try (Transaction tx = graphService.beginTx()) {
UniqueFactory.UniqueNodeFactory uniqueFactory = createUserFactory(graphService);
uniqueFactory.getOrCreate("userId", 100L);
tx.success();
}
}
}
錯誤:
Caused by: org.neo4j.kernel.api.exceptions.schema.UniquePropertyConstraintViolationKernelException: Node 0 already exists with label 0 and property 0=100
at org.neo4j.kernel.impl.api.ConstraintEnforcingEntityOperations.validateNoExistingNodeWithLabelAndProperty(ConstraintEnforcingEntityOperations.java:165)
at org.neo4j.kernel.impl.api.ConstraintEnforcingEntityOperations.nodeSetProperty(ConstraintEnforcingEntityOperations.java:140)
at org.neo4j.kernel.impl.api.LockingStatementOperations.nodeSetProperty(LockingStatementOperations.java:453)
at org.neo4j.kernel.impl.api.OperationsFacade.nodeSetProperty(OperationsFacade.java:896)
at org.neo4j.kernel.impl.core.NodeProxy.setProperty(NodeProxy.java:293)
... 33 more