views:

1666

answers:

1

Hi all,

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

+2  A: 

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.

johnstok
"if you begin manipulating the objects in the list returned from this method, [...] those changes will be propagated back to the database out-with a transaction on an ad-hoc basis." Does that apply for withTransaction turned off or for both case ?
Frederic Morin
If it apply to both case, and if I call em.clear() at the end of the function the entities will then be in detached mode and nothing will be automatically sent/commited to the db. Right ?
Frederic Morin
Or should I understand that: if I don't enforce transaction in my select and do the transaction management a level higher (outside this function) I will then be able to wrap the select and the modification of the entities all within a transaction and this will prevent ad-hoc (autocommit) mode.
Frederic Morin