Maria
Maria

Reputation: 1211

Read only service : javax.persistence.TransactionRequiredException: no transaction is in progress

I have a service that reads data from database. After reading there is a flush which causes the exception mentioned in the title. Below is the sequence of statements

    ManagerFactory factory = new ManagerFactory();
    EntityManager manager = factory.getManager();
    EntityTransaction transaction = manager.getTransaction();

    Query query = manager.createQuery("select personRoleJPA from personRoleJPA");
    personRoleJPA = (PersonRoleJPA) query.getSingleResult();

    if (manager.isOpen()) {
       manager.flush();
    }
    if (manager.isOpen()) {
       manager.close();
       manager = null;
    }
    if (transaction.isActive()) {
     transaction.commit();
   }

I suspect the exception is because I did not begin the transaction. My question is do you really need to flush & commit when you are not doing any writes ?

Upvotes: 0

Views: 434

Answers (2)

Hussein Zawawi
Hussein Zawawi

Reputation: 2927

Remove everything related to transaction since you dont need an active transaction to retrieve data:

ManagerFactory factory = new ManagerFactory();
    EntityManager manager = factory.getManager();

    Query query = manager.createQuery("select personRoleJPA from personRoleJPA");
    personRoleJPA = (PersonRoleJPA) query.getSingleResult();

    if (manager.isOpen()) {
       manager.flush();
    }
    if (manager.isOpen()) {
       manager.close();
       manager = null;
    }

Upvotes: 1

Afsun Khammadli
Afsun Khammadli

Reputation: 2068

About flush() method you can read from documentation:http://docs.oracle.com/javase/1.5.0/docs/api/java/io/OutputStream.html#flush%28%29
If you read anything from database you do not need transaction.commit().commit() using for saving changes after sql statement executed but in select statement you do not need commit.Default in JDBC commit is auto-commit mode.In hibernate configuration file you can change this settings.The best practice is disabling auto-commit mode.
About commit() you can also read from:https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html

Upvotes: 0

Related Questions