Java – How JPA (Hibernate) deal with transaction when fetching Object from database

hibernatejavajpatransactions

I'm currently developping an application in java using Hibernate as a persistence manager and JPA as an abstraction of the persistence manage hibernate.

I'd like to know the impact of wrapping a result query around a transaction. I know the entity manager must stay open for lazily fetched field bug what about transaction in all this ?

Here is a code example with transaction activation/desactivation ability.

public List<Exportdata> get(Integer max, EntityManager em, Boolean withTransaction) {
    EntityTransaction tx = null;
    try {
        if (withTransaction) {
            tx = em.getTransaction();
            tx.begin();
        }

        Query query = em.createQuery("from Exportdata");
        query.setMaxResults(10);
        List<Exportdata> list = query.getResultList();

        if (withTransaction)
            tx.commit();

        return list;
    } catch (RuntimeException re) {
        if (withTransaction)
            if (tx != null && tx.isActive())
                tx.rollback();

        throw re;
    }
}

What is the difference between enabling or disabling withTransaction when this function is called ?

Thanks all,
Fred

Best Solution

There is no practical difference here, since you aren't changing any data. The query you execute will generate an SQL select. Transactions are there to allow you to apply ACID properties to a collection of inserts, updates, etc.

However, if you begin manipulating the objects in the list returned from this method, calling setters, etc. those changes will be propagated back to the database out-with a transaction on an ad-hoc basis. In other words you'll effectively be working with the db in auto-commit mode. This is unlikely to be what you want.

The important thing to understand is that the duration of a persistence context and a transaction can be managed separately. Often though you would want to manage them together.