我目前遇到的问题是,@Transactional注释似乎还没有为Neo4j启动事务(它不适用于我的任何@ transaction注释方法,而不仅仅是下面的示例)。
示例:
我有这个方法(UserService.createUser),它首先在Neo4j图中创建一个用户节点,然后在MongoDB中创建用户(包含其他信息)。(MongoDB不支持事务,因此首先创建用户节点,然后将实体插入MongoDB,然后提交Neo4j事务)。
这个方法是用@Transactional注释的,但是当在Neo4j中创建用户时,会抛出一个org.neo4j.graphdb.NotInTransactionException。
是关于我的配置和编码的,分别是:
基于代码的SDN-Neo4j配置:
@Configuration
@EnableTransactionManagement // mode = proxy
@EnableNeo4jRepositories(basePackages = "graph.repository")
public class Neo4jConfig extends Neo4jConfiguration {
private static final String DB_PATH = "path_to.db";
private static final String CONFIG_PATH = "path_to.properties";
@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(DB_PATH)
.loadPropertiesFromFile(CONFIG_PATH).newGraphDatabase();
}
}用于在Neo4j和MongoDB中创建用户的服务:
@Service
public class UserService {
@Inject
private UserMdbRepository mdbUserRepository; // MongoRepository
@Inject
private Neo4jTemplate neo4jTemplate;
@Transactional
public User createUser(User user) {
// Create the graph-node first, because if this fails the user
// shall not be created in the MongoDB
this.neo4jTemplate.save(user); // NotInTransactionException is thrown here
// Then create the MongoDB-user. This can't be rolled back, but
// if this fails, the Neo4j-modification shall be rolled back too
return this.mdbUserRepository.save(user);
}
...
}侧记:
3.2.3.RELEASE和Spring-Data-ne4j版本的2.3.0.M1有没有人知道为什么这不起作用(现在)?
我希望这些资料是足够的。如果遗漏了什么,请告诉我,我会加进去的。
编辑:
我忘了提到手动事务处理工作,但我当然想以“它的本意”的方式来实现它。
public User createUser(User user) throws ServiceException {
Transaction tx = this.graphDatabaseService.beginTx();
try {
this.neo4jTemplate.save(user);
User persistantUser = this.mdbUserRepository.save(user);
tx.success();
return persistantUser;
} catch (Exception e) {
tx.failure();
throw new ServiceException(e);
} finally {
tx.finish();
}
}发布于 2013-09-06 14:22:16
幸亏我终于发现了这个问题。问题是,与配置SDN-Neo4j的位置相比,我在一个不同的spring配置文件中扫描了这些组件/服务。我将那些可能需要事务的组件扫描移到我的Neo4jConfig上,现在它可以工作了。
@Configuration
@EnableTransactionManagement // mode = proxy
@EnableNeo4jRepositories(basePackages = "graph.repository")
@ComponentScan({
"graph.component",
"graph.service",
"core.service"
})
public class Neo4jConfig extends Neo4jConfiguration {
private static final String DB_PATH = "path_to.db";
private static final String CONFIG_PATH = "path_to.properties";
@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(DB_PATH)
.loadPropertiesFromFile(CONFIG_PATH).newGraphDatabase();
}
}不过,我仍然需要将需要事务的组件/服务与不需要事务的组件/服务分开。然而,这暂时起作用了。
我假设问题是另一个春季配置文件(包括组件扫描)是在Neo4jConfig之前加载的,因为neo4j:repositories必须放在context:component-scan之前。(见例20.26中的注)。合成存储库http://static.springsource.org/spring-data/data-neo4j/docs/current/reference/html/programming-model.html#d0e2948)
https://stackoverflow.com/questions/18640916
复制相似问题