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();

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

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s