一:试图通过配置的方式给springMVC的控制器加事务失败
一般而言,事务都是加在Service层的,但是爱钻牛角尖的我时常想:事务加在Controller层可不可以。我一直试图证明事务不止可以加在Service层,还可以加在Controller层,但是没有找到有力的论据来支持我这个想法,搞得我一度认为事务只能加在Service层,直到我读过spring官方文档并实践之后,我知道我的想法是对的。
Connection = null;
PreparedStatement pstmt = null;
try{
con = DriverManager.getConnection(dbUrl, username, password);
//设置手工提交事务模式
con.setAutoCommit(false);
pstmt = ……;
pstmt.executeUpdate();
//提交事务
con.commit();
}catch(Exception e){
//事务回滚
con.rollback();
…..
} finally{
…….
}
SessionFactory factory=new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();
Employee ee=new Employee();
ee.setComm(1.6f);
ee.setEname("fuck11111");
Session session=factory.openSession();
session.setHibernateFlushMode(FlushMode.MANUAL);
Transaction tx=session.beginTransaction();
session.save(ee);
tx.commit();//即使commit也无法持久化数据
三
:spring接管事务管理后
if (definition.isReadOnly() && txObject.isNewSessionHolder()) {
// Just set to NEVER in case of a new Session for this transaction.
session.setFlushMode(FlushMode.NEVER);
}
if (!definition.isReadOnly() && !txObject.isNewSessionHolder()) {
// We need AUTO or COMMIT for a non-read-only transaction.
FlushMode flushMode = session.getFlushMode();
if (FlushMode.NEVER.equals(flushMode)) {
session.setFlushMode(FlushMode.AUTO);
txObject.getSessionHolder().setPreviousFlushMode(flushMode);
}
}
openSessionInView延长了session的生命周期
导致一些弊端,还是不推荐使用