Java TransactionException:事务未成功启动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24657977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TransactionException: Transaction not successfully started
提问by
I have following dao:
我有以下道:
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Transactional
public void add(User user) {
Session session = sessionFactory.getCurrentSession();
session.save(user);
session.getTransaction().commit();
}
}
it is invokes from
它是从
@Controller
public class HomeController {
@Autowired
private UserDao userDao;
@RequestMapping(value = "/test")
public ModelAndView test() {
User user = new User();
user.setName("34r");
userDao.add(user);
ModelAndView model = new ModelAndView("home");
model.addObject("userList", null);
return model;
}
}
in browser I try to access to this link
在浏览器中,我尝试访问此链接
And finally I get following stacktrace:
最后我得到以下堆栈跟踪:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/SpringMvcHibernateXML] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started] with root cause
org.hibernate.TransactionException: Transaction not successfully started
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:172)
I have following configuration:
我有以下配置:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
How to fix this problem?
如何解决这个问题?
采纳答案by Zeus
You should not do session.getTransaction().commit();
this, the @transactional will take care of it. Remove it, you should be fine.
你不应该这样做session.getTransaction().commit();
,@transactional 会处理它。删除它,你应该没问题。
回答by Sthogari
where you begin the transaction. i can't see this line session.beginTrainsaction(); once you begin the transaction then only you can commit and rollback
您开始交易的地方。我看不到这一行 session.beginTrainsaction(); 一旦您开始事务,那么只有您可以提交和回滚