-1

I cannot save my entity data into database without transaction. I know PersistenceContextType.Extend, But I cannot success.


@NoTransaction
public class Application extends Controller {

    public static void create(String body) {
        // EntityTransaction tm = JPA.em().getTransaction();
        if (!JPA.isEnabled()) {
            System.out.println("JPA is not initialized");
        }
        EntityManager manager = JPA.entityManagerFactory.createEntityManager();
        //manager.setFlushMode(FlushModeType.COMMIT);
        manager.setProperty("org.hibernate.readOnly", false);
        //new Customer("001").save();
        if (!JPA.isInsideTransaction()) {
        //  manager.getTransaction().begin();
        }
        createContext(manager, false);
        new Customer("001").save();
        //manager.getTransaction().commit();
        /*
         * if (tm.equals(null)) { System.out.println("success"); }
         */
    }

    static void createContext(EntityManager entityManager, boolean readonly) {
        if (JPA.local.get() != null) {
            try {
                JPA.local.get().entityManager.close();
            } catch (Exception e) {
                // Let's it fail
            }
            JPA.local.remove();
        }
        JPA context = new JPA();
        context.entityManager = entityManager;
        // context.readonly = readonly;
        JPA.local.set(context);
    }
}

I initialed the JPA by myself to prevent play from starting a transaction. I want to save my data into database, but I get a TransactionRequiredException error. I known that JPA operation need a transaction, but I want to know whether has a exception.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Glowd
  • 31
  • 4

1 Answers1

0

I am not really sure what you are trying to achieve here. It is best to let Play handle transactions. You will not be able to commit your changes without a transaction.

If you need more control as to when the transaction is commited you could use a utility method like:

public static void commit() {
    if (JPA.em().getTransaction().getRollbackOnly()) {
        JPA.em().getTransaction().rollback();
    } else {
        JPA.em().getTransaction().commit();
    }
    JPA.em().getTransaction().begin();
    JPA.em().flush();
    JPA.em().clear();
}
emt14
  • 4,846
  • 7
  • 37
  • 58