java - 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
解决方案
推荐阅读
- aggregation - 在 Grafana for Prometheus 中获取查询的最大值
- api - BigCommerce 订单 API 空错误响应
- angular - 在 Angular Universal 中将 json 文件设置为路由
- python - 有多个空格时如何 re.split(" ", string)?
- python-2.7 - 输入键命令有时在预期中不起作用
- python - 如何在现有的朴素贝叶斯算法(Python 3)中测试新数据
- python - Python 使用 Lamda 函数附加到 Tkinter 按钮
- regex - 如何在 PowerShell 中使用 $regex 组合多个模式搜索并生成单行输出
- java - 如何使用 java mail api 发送任何类型的附件?
- r - ggplot2:theme_void() 与 theme_set() 一起使用时会引发警告