Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transac

本文详细解析了Hibernate框架中关于事务管理的问题,特别是在使用getCurrentSession方法时需要注意的事项。通过示例代码展示了如何正确地开启和提交事务,避免因未在事务环境中使用会话而导致的HibernateException异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:341)
at com.sun.proxy.$Proxy0.get(Unknown Source)
at dao.UserDao.getUser(UserDao.java:10)
at biz.UserBiz.getUser(UserBiz.java:18)

at test.Test.main(Test.java:9)


在使用getCurrentSession();方法创建会话获得会话时,出现Exception in thread "main" org.hibernate.HibernateException: 异常


那是因为使用此会话进行的jdbc操作,必须是要在开启事物的环境下进行


public User getUser(int id) {
Transaction tx = null;
User user = null;
try {
tx = HibernateSessionFactory.getSession().beginTransaction();
user = dao.getUser(id);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
if(tx != null) {
tx.rollback();
}
}
return  user;
}


业务层必须要获得transaction事物对象,进行commit 和 rollback


如果直接去调用(User) HibernateSessionFactory.getSession().get(User.class, id);

就会出现此异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值