This article mainly introduces how to handle transactions in our development process, of course, the programming language is limited to java.
The content of the article will be explained one by one from how to deal with transactions directly with jdbc without using any framework, to using mybatis and hibernate.
1. JDBC transactions.
JDBC transactions are completed through the Connection object, the main logic is as follows
//After getting the Connection object, the settings are not automatically submitted conn.setAutoCommit(false); //manually submit conn.commit(); // rollback of the transaction conn.rollback();
Second, mybatis affairs
The following is from the documentation
http://mybatis.github.io/mybatis-3/configuration.html#environments
Mybatis supports two types of transactions JDBC|MANAGED, we can set in the following
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="..." value="..."/> </transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments>
Note that there is a property attribute in the transaction, which is mainly used when type=MANAGED
<transactionManager type="MANAGED"> <property name="closeConnection" value="false"/> </transactionManager>
Because the connection is closed by default, but some containers do not want to close, they may also use the container to do some other things, so it can be controlled through this property.
Use the following steps
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream(file)); SqlSession session = sqlSessionFactory.openSession(false); //The setting is not automatically submitted try { BlogMapper mapper = session.getMapper(BlogMapper.class); mapper.updateBlog(blog); mapper.increaseOperation(); session.commit(); //manual commit }catch(Exception e){ e.printStackTrace (); session.rollback(); //rollback } finally { session.close(); }
After careful comparison, we found that it is basically the same. In fact, the framework uses basic APIs, so you need to pay attention to basic knowledge at any time.
Want to know how mybatis implements transaction management, click on MyBatis transaction management source code
Three, hibernate transaction
//EVERYTHING