我是图形数据库的新手,我在让 api 在事务中工作时遇到了问题。
我有一个简单的代码,它使用 neo4j graph db api 创建节点和关系。我的代码在 JUnit 中运行,并尝试使用下面给出的开始和结束事务创建 2 个节点以及它们之间的关系。
该代码在快乐的情况下工作正常。但是,如果代码中出现问题,节点仍会提交到图形数据库中。不知道我在这里做错了什么。我本来希望创建的 2 个节点被回滚。
这是代码片段:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class RestBatchLoaderTest {
@Autowired
SpringRestGraphDatabase graphDatabaseService;
@Test
public void createNode() {
Transaction tx =graphDatabaseService.beginTx();
try {
Map<String,Object> nodeprops1 = new HashMap<String, Object>();
nodeprops1.put("name", "James Parker");
nodeprops1.put("age", Integer.valueOf(11));
Node james = graphDatabaseService.createNode(nodeprops1);
Assert.assertNotNull(james);
Map<String,Object> nodeprops2 = new HashMap<String, Object>();
nodeprops2.put("name", "Bing P");
nodeprops2.put("age", Integer.valueOf(34));
Node bing= graphDatabaseService.createNode(nodeprops2);
Node aa = null;
// Failure point: should rollback the previous node in the finally.
graphDatabaseService.remove(aa);
Map<String,Object> relprops = new HashMap<String, Object>();
RelationshipType type = new RelationshipType() {
@Override
public String name() {
return "MARRIED_TO";
}
};
graphDatabaseService.createRelationship(joe, jane, type, relprops);
tx.success();
} finally {
tx.finish();
}
}
graphDatabaseService对象是使用 spring 配置自动装配的。这是配置:
<neo4j:config graphDatabaseService="graphDatabaseService"/>
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
<constructor-arg value="http://localhost:7474/db/data/"/>
</bean>
另外,我注意到在上面的代码中调用graphDatabaseService.beginTx()时, tx对象是NullTransaction的一个实例。
任何想法,出了什么问题?
谢谢。