使用SessionFactory时,事务管理在neo4j-omg中不起作用

问题描述

我编写了一个小的Spring Boot应用程序,它使用spring-boot-starter-data-neo4j连接到Neo4j实例。

我想通过Cypher查询执行一些更新,但是使用Session打开SessionFactory时无法使事务管理正常工作。通过Neo4jRepository使用带有OGM注释的实体,事务管理工作正常。

出于测试目的,我编写了两个用@Transactional注释的简单服务:

使用带OGM注释的类和Neo4jRepository

@Service
@Transactional
public class OgmServiceImpl implements OgmService {
    private final PersonRepository personRepository;

    public OgmServiceImpl(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @Override
    public void storeData() {
        personRepository.save(new Person("Jack"));
        if (true) {
            throw new IllegalStateException();
        }
        personRepository.save(new Person("Jill"));
    }
}

执行storeData()方法时,Jack和Jill均不会保存到Neo4j。按预期工作。

另一项服务通过在Neo4j Session上执行Cypher查询来完成相同的工作:

@Service
@Transactional
public class CypherServiceImpl implements CypherService {
    private final SessionFactory sessionFactory;

    public CypherServiceImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void storeData() {
        Session session = sessionFactory.openSession();
        session.query("CREATE (p:Person { name: 'Jack' })",Map.of());
        if (true) {
            throw new IllegalStateException();
        }
        session.query("CREATE (p:Person { name: 'Jill'})",Map.of());
    }
}

但是,由于Jack存储在Neo4j中,所以事务管理失败。

对我来说,这种行为是出乎意料的。我可以通过显式启动事务来使事务管理正常工作,但这不是我喜欢的方式:

    public void storeData() {
        Session session = sessionFactory.openSession();
        try (Transaction tx = session.beginTransaction()) {
            session.query("CREATE (p:Person { name: 'Jack' })",Map.of());
            if (true) {
                throw new IllegalStateException();
            }
            session.query("CREATE (p:Person { name: 'Jill'})",Map.of());
            tx.commit();
        }
    }

我需要自己配置SessionFactory才能使其正常工作吗?为什么Spring Boot不解决这个问题?

解决方法

只看了docs。根据文档,当您以编程方式调用SessionFactory#openSession时,会创建一个全新的会话,该会话不一定在由@Transactional注释指定的交易范围中。

要进一步确保这一点,您可以尝试使用以下代码检查断言错误:

@Override
public void storeData() {
    Session session = sessionFactory.openSession();
    assert session.getTransaction() != null;

    session.query("CREATE (p:Person { name: 'Jack' })",Map.of());       
    session.query("CREATE (p:Person { name: 'Jill'})",Map.of());
} 

这将导致断言错误。与提供a way of getting the current session的休眠模式不同,我找不到neo4J-ogm方法。

下面编写的代码之所以有效,是因为即使您创建了一个全新的Session,也会由您管理事务。在这里,虽然不是一个好主意,但您正在创建一个自我管理的事务,而不是Spring容器管理的事务。

public void storeData() {
    Session session = sessionFactory.openSession();
    try (Transaction tx = session.beginTransaction()) {
        session.query("CREATE (p:Person { name: 'Jack' })",Map.of());
        if (true) {
            throw new IllegalStateException();
        }
        session.query("CREATE (p:Person { name: 'Jill'})",Map.of());
        tx.commit();
    }
}