6

I was following a tutorial on Hibernate and saw the following code:

package com.websystique.spring.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractDao {

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public void persist(Object entity) {
        getSession().persist(entity);
    }

    public void delete(Object entity) {
        getSession().delete(entity);
    }
}

I was wondering if persist() (or save() or delete()) can be used without a transaction? As it seems to be the case here.

Matthew
  • 8,183
  • 10
  • 37
  • 65
Liumx31
  • 1,190
  • 1
  • 16
  • 33

3 Answers3

6

you cant save or persist object without transaction you have to commit the transaction after saving the object otherwise it won't save in database. Without transaction you can only retrieve object from database

GAURAV ROY
  • 1,885
  • 1
  • 12
  • 4
1

As said you CAN'T save anything in the database without a active transaction. It seens that you are using a container, in this case Spring. Spring can control transactions by interceptos like JavaEE. You can read more here: http://docs.jboss.org/weld/reference/2.4.0.Final/en-US/html/interceptors.html

Also this looks like a really poor example to demonstrate:

public class TransactionalInterceptor {

    @Inject
    private Session session;

    @AroundInvoke
    public Object logMethodEntry(InvocationContext ctx) throws Exception {
        Object result = null;
        boolean openTransaction = !session.getTransaction().isActive();
        if(openTransaction)
            session.getTransaction().begin();
        try {
            result = ctx.proceed();
            if(openTransaction)
                session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
            throw new TransactionException(e);
        }
        return result;
    }

}
Bruno Manzo
  • 353
  • 3
  • 15
1

Actually, IT IS POSSIBLE to persist without a transaction with Hibernate but it's STRONGLY DISCOURAGED because of performance and data consistency issues.

application.properties:

hibernate.allow_update_outside_transaction=true

Spring application.properties:

spring.jpa.properties.hibernate.allow_update_outside_transaction=true

As I had to use this setting for a very specific reason. I think it might be of use to some people, even though it's not recommended to be used in production code.

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29