首页 > 解决方案 > Hibernate:我应该在抽象 dao 中包含 begin transaction 和 commit 吗?

问题描述

我正在尝试从 Baeldung 的一篇文章中实现 AbstractHibernateDao,但是当我运行代码时,出现如下错误:

如果没有活动事务,调用方法“persist”无效(当前状态:NOT_ACTIVE)

我知道代码中看到的每个方法都需要一个开始并提交一个事务才能工作,并且一旦我这样做了它就会很好地工作。

文章中是否根本没有包含开始事务和提交以保持简短,或者我缺少某些配置?

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();
  }
}

我正在使用 Spring 学习 Hibernate 和最佳实践。这是 Baeldung 的文章https://www.baeldung.com/persistence-layer-with-spring-and-hibernate

标签: javaspringhibernate

解决方案


推荐阅读