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.
Detached instances may be made persistent by calling update() , saveOrUpdate() , lock() or replicate() . The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge() .
Save() and persist() both methods are used for saving object in the database. Save() − Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.)
First difference between save and persist is there return type. Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.
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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With