【发布时间】:2014-02-03 07:02:30
【问题描述】:
我在独立模式下使用 Neo4j,在我的应用程序中使用 Spring Data for Neo4j。我的代码需要能够确保当我尝试保存一个对象时,要么一切都进入,要么什么都不做。我知道 Spring Neo4j 中的 REST 不支持事务,但是 Neo4j 的 REST API 中的 batch operation 应该可以满足我当前的需求。没有那么多操作,但整个 save() 调用需要是全有或全无的事情。
然而,Spring 似乎默认不这样做。如果在写入过程中发生 RuntimeException,仍然会有一些部分数据放入数据库中。我想继续使用 GraphRepository 接口,但如果这不可能,我想我可以手动实现它。
这里有一些简化的示例代码来说明发生了什么
POJO:
@NodeEntity
public class TestObject {
@GraphId
private Long id;
private String name;
@Fetch
@RelatedTo(type = "SIBLING_OF", direction = Direction.BOTH)
private Set<TestObject> siblings;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
if (name == "fail") {
throw new RuntimeException();
}
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TestObject> getSiblings() {
return siblings;
}
public void setSiblings(Set<TestObject> siblings) {
this.siblings = siblings;
}
}
存储库
public interface TestRepository extends GraphRepository<TestObject>{}
测试
public class Test {
@Autowired
TestRepository repo;
public void run() {
final TestObject o1 = new TestObject();
o1.setName("good1");
final TestObject o2 = new TestObject();
o1.setName("good2");
final TestObject o3 = new TestObject();
o1.setName("good3");
final TestObject o4 = new TestObject();
o1.setName("fail");
o1.setSiblings(new HashSet<TestObject>() {{
add(o2);
add(o3);
add(o4);
}});
//throws exception, but o1 node is created in Neo4j
repo.save(o1);
}
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("context.xml");
Test t = (Test) appContext.getBean("test");
t.run();
}
}
【问题讨论】:
标签: java spring neo4j spring-data-neo4j