Java – DataBase access – basic class

This is a basic class to access a database using a persistence.xml file. This class has already 3 methods to handle the transactions.

public class DBaccess {

    private final EntityManagerFactory factory;
    private final EntityManager manager;
    private EntityTransaction transaction;

    public DBaccess() {
        factory = Persistence.createEntityManagerFactory("myPersistenceUnit");
        manager = factory.createEntityManager();
    }

    private void startTransaction() {
        transaction = manager.getTransaction();
        transaction.begin();
    }

    private void commit() {
        if (transaction != null) {
            transaction.commit();
        }
        transaction = null;
    }

    private void rollback() {
        if (transaction != null) {
            transaction.rollback();
        }
        transaction = null;
    }
}