No active transaction for _MAIN_ database


I want to initialize a list from a database whenever an item is added/updated or removed.

In my Service Class I have the method below:

private static final List<MyClass> MY_LIST = new ArrayList<>();

private Persistence persistence;

public void initMyClasses() {"Initialize MY_LIST");
    EntityManager entityManager = persistence.getEntityManager();
    List<MyClass> myClasses = entityManager.createQuery("select b from ash_MyClass b ").getResultList();

Then I added a Changed Listener on MyClass entity to call initMyClasses everytime there is update/create/delete.

private MyClassService myClassService;

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void afterCompletion(EntityChangedEvent<MyClass, UUID> event) {

When I run the application and do any update on UI, I get this error.

java.lang.IllegalStateException: No active transaction for MAIN database
at com.haulmont.cuba.core.sys.PersistenceImpl.getEntityManager( ~[cuba-core-7.2.4.jar:7.2.4]
at com.haulmont.cuba.core.sys.PersistenceImpl.getEntityManager( ~[cuba-core-7.2.4.jar:7.2.4]

Read the docs:

In “after commit” listeners ( TransactionPhase.AFTER_COMMIT ), use DataManager or explicitly create a new transaction before using TransactionalDataManager .

Most likely you can rewrite your code to use DataManager instead of EntityManager and @Transactional. Using DataManager or TransactionalDataManager is recommended compared to low-level EntityManager in most cases.