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