5

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
  • 7,763
  • 10
  • 36
  • 64
Liumx31
  • 1,146
  • 1
  • 13
  • 31

2 Answers2

5

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,875
  • 1
  • 11
  • 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
  • 333
  • 3
  • 13