0

I am trying to implement the AbstractHibernateDao from one of Baeldung's article but when I run the code I get the error as below:

Calling method 'persist' is not valid without an active transaction (Current status: NOT_ACTIVE)

I understand that every method as seen in the code needs a begin and commit a transaction to work and it worked well once I did.

Was the begin transaction and commit simply not included in the article for keeping it short or am I missing on some configuration?

public abstract class AbstractHibernateDao< T extends Serializable > {

private Class< T > clazz;

@Autowired
SessionFactory sessionFactory;

public final void setClazz( Class< T > clazzToSet ){
   this.clazz = clazzToSet;
}

public T findOne( long id ){
  return (T) getCurrentSession().get( clazz, id );
}
public List< T > findAll(){
  return getCurrentSession().createQuery( "from " + clazz.getName() 
  ).list();
}

public void create( T entity ){
  getCurrentSession().persist( entity );
}

public void update( T entity ){
 getCurrentSession().merge( entity );
}

public void delete( T entity ){
 getCurrentSession().delete( entity );
}
public void deleteById( long entityId ) {
  T entity = findOne( entityId );
  delete( entity );
}

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

I am learning Hibernate and best practices with Spring. Here is the Baeldung's article https://www.baeldung.com/persistence-layer-with-spring-and-hibernate

Durja
  • 637
  • 13
  • 20
  • 1
    I think you are using a mode where you have to open and close the transactions in your source code. But it is possible that spring handles the transactions for you. Maybe this will help you: https://stackoverflow.com/questions/758050/automatic-hibernate-transaction-management-with-spring – Andreas Hauschild Jan 03 '19 at 11:13
  • 2
    Usually "transaction template" is not a part of DAO. if you use spring transaction management, then still @Transaction annotation should not be in the DAO . this is due to various reasons (ex: access lazy load entities or collections) – hunter Jan 03 '19 at 11:21

0 Answers0