发表于: 2019-11-11 23:58:45
1 989
今天完成的事情:(一定要写非常细致的内容,比如说学会了盒子模型,了解了Margin)
今天又没有做什么事,刷了牛客网的一套题。自己的基础还是很差。
Mybatis管理事务是分为两种方式:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <environments default="development">
- <environment id="development">
- <!--配置事务的管理方式-->
- <transactionManager type="JDBC" />
- <!-- 配置数据库连接信息 -->
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
- <property name="username" value="root" />
- <property name="password" value="XDP" />
- </dataSource>
- </environment>
- </environments>
- </configuration>
Mybatis提供了一个事务接口Transaction,以及两个实现类jdbcTransaction和ManagedTransaction,当spring与Mybatis一起使用时,spring提供了一个实现类SpringManagedTransaction
Transaction接口:提供的抽象方法有获取数据库连接getConnection,提交事务commit,回滚事务rollback和关闭连接close,源码如下:
- //事务接口
- ublic interface Transaction {
- /**
- * Retrieve inner database connection
- * @return DataBase connection
- * @throws SQLException
- */
- //获得数据库连接
- Connection getConnection() throws SQLException;
- /**
- * 提交
- * Commit inner database connection.
- * @throws SQLException
- */
- void commit() throws SQLException;
- /**
- * 回滚
- * Rollback inner database connection.
- * @throws SQLException
- */
- void rollback() throws SQLException;
- /**
- * 关闭连接
- * Close inner database connection.
- * @throws SQLException
- */
- void close() throws SQLException;
JdbcTransaction实现类:Transaction的实现类,通过使用jdbc提供的方式来管理事务,通过Connection提供的事务管理方法来进行事务管理,源码如下:
- public class JdbcTransaction implements Transaction {
- private static final Log log = LogFactory.getLog(JdbcTransaction.class);
- /* 连接**/
- protected Connection connection;
- /* 数据源**/
- protected DataSource dataSource;
- /* 事务等级**/
- protected TransactionIsolationLevel level;
- /* 事务提交**/
- protected boolean autoCommmit;
- public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
- dataSource = ds;
- level = desiredLevel;
- autoCommmit = desiredAutoCommit;
- }
- public JdbcTransaction(Connection connection) {
- this.connection = connection;
- }
- @Override
- public Connection getConnection() throws SQLException {
- if (connection == null) {
- openConnection();
- }
- //返回连接
- return connection;
- }
- @Override
- public void commit() throws SQLException {
- if (connection != null && !connection.getAutoCommit()) {
- if (log.isDebugEnabled()) {
- log.debug("Committing JDBC Connection [" + connection + "]");
- }
- //连接提交
- connection.commit();
- }
- }
- @Override
- public void rollback() throws SQLException {
- if (connection != null && !connection.getAutoCommit()) {
- if (log.isDebugEnabled()) {
- log.debug("Rolling back JDBC Connection [" + connection + "]");
- }
- //连接回滚
- connection.rollback();
- }
- }
- @Override
- public void close() throws SQLException {
- if (connection != null) {
- resetAutoCommit();
- if (log.isDebugEnabled()) {
- log.debug("Closing JDBC Connection [" + connection + "]");
- }
- //关闭连接
- connection.close();
- }
- }
- protected void setDesiredAutoCommit(boolean desiredAutoCommit) {
- try {
- //事务提交状态不一致时修改
- if (connection.getAutoCommit() != desiredAutoCommit) {
- if (log.isDebugEnabled()) {
- log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]");
- }
- connection.setAutoCommit(desiredAutoCommit);
- }
- } catch (SQLException e) {
- // Only a very poorly implemented driver would fail here,
- // and there's not much we can do about that.
- throw new TransactionException("Error configuring AutoCommit. "
- + "Your driver may not support getAutoCommit() or setAutoCommit(). "
- + "Requested setting: " + desiredAutoCommit + ". Cause: " + e, e);
- }
- }
- protected void resetAutoCommit() {
- try {
- if (!connection.getAutoCommit()) {
- // MyBatis does not call commit/rollback on a connection if just selects were performed. select操作没有commit和rollback事务
- // Some databases start transactions with select statements 一些数据库在select操作是会开启事务
- // and they mandate a commit/rollback before closing the connection.
- // A workaround is setting the autocommit to true before closing the connection.
- // Sybase throws an exception here.
- if (log.isDebugEnabled()) {
- log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
- }
- connection.setAutoCommit(true);
- }
- } catch (SQLException e) {
- if (log.isDebugEnabled()) {
- log.debug("Error resetting autocommit to true "
- + "before closing the connection. Cause: " + e);
- }
- }
- }
- //打开连接
- protected void openConnection() throws SQLException {
- if (log.isDebugEnabled()) {
- log.debug("Opening JDBC Connection");
- }
- //从数据源中获得连接
- connection = dataSource.getConnection();
- if (level != null) {
- connection.setTransactionIsolation(level.getLevel());
- }
- setDesiredAutoCommit(autoCommmit);
- }
- }
ManagedTransaction实现类:通过容器来进行事务管理,所有它对事务提交和回滚并不会做任何操作,源码如下:
- public class ManagedTransaction implements Transaction {
- private static final Log log = LogFactory.getLog(ManagedTransaction.class);
- private DataSource dataSource;
- private TransactionIsolationLevel level;
- private Connection connection;
- private boolean closeConnection;
- public ManagedTransaction(Connection connection, boolean closeConnection) {
- this.connection = connection;
- this.closeConnection = closeConnection;
- }
- //数据源,事务等级及是否关闭事务
- public ManagedTransaction(DataSource ds, TransactionIsolationLevel level, boolean closeConnection) {
- this.dataSource = ds;
- this.level = level;
- this.closeConnection = closeConnection;
- }
- @Override
- public Connection getConnection() throws SQLException {
- if (this.connection == null) {
- openConnection();
- }
- return this.connection;
- }
- //提交操作无效
- @Override
- public void commit() throws SQLException {
- // Does nothing
- }
- //回滚操作无效
- @Override
- public void rollback() throws SQLException {
- // Does nothing
- }
- @Override
- public void close() throws SQLException {
- if (this.closeConnection && this.connection != null) {
- if (log.isDebugEnabled()) {
- log.debug("Closing JDBC Connection [" + this.connection + "]");
- }
- //关闭连接
- this.connection.close();
- }
- }
- protected void openConnection() throws SQLException {
- if (log.isDebugEnabled()) {
- log.debug("Opening JDBC Connection");
- }
- this.connection = this.dataSource.getConnection();
- if (this.level != null) {
- this.connection.setTransactionIsolation(this.level.getLevel());
- }
- }
- }
SpringManagedTransaction实现类:它其实也是通过使用JDBC来进行事务管理的,当spring的事务管理有效时,不需要操作commit/rollback/close,spring事务管理会自动帮我们完成,源码如下:
- public class SpringManagedTransaction implements Transaction {
- private static final Log LOGGER = LogFactory.getLog(SpringManagedTransaction.class);
- private final DataSource dataSource;
- private Connection connection;
- private boolean isConnectionTransactional;
- private boolean autoCommit;
- //获得数据源
- public SpringManagedTransaction(DataSource dataSource) {
- notNull(dataSource, "No DataSource specified");
- this.dataSource = dataSource;
- }
- /**
- * {@inheritDoc}
- * 返回数据库连接
- */
- @Override
- public Connection getConnection() throws SQLException {
- if (this.connection == null) {
- openConnection();
- }
- return this.connection;
- }
- /**
- * Gets a connection from Spring transaction manager and discovers if this
- * {@code Transaction} should manage connection or let it to Spring.
- * <p>
- * It also reads autocommit setting because when using Spring Transaction MyBatis
- * thinks that autocommit is always false and will always call commit/rollback
- * so we need to no-op that calls.
- *从spring的事务管理中获得一个连接
- */
- private void openConnection() throws SQLException {
- this.connection = DataSourceUtils.getConnection(this.dataSource);
- this.autoCommit = this.connection.getAutoCommit();
- this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(
- "JDBC Connection ["
- + this.connection
- + "] will"
- + (this.isConnectionTransactional ? " " : " not ")
- + "be managed by Spring");
- }
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public void commit() throws SQLException {
- if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Committing JDBC Connection [" + this.connection + "]");
- }
- this.connection.commit();
- }
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public void rollback() throws SQLException {
- if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Rolling back JDBC Connection [" + this.connection + "]");
- }
- this.connection.rollback();
- }
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public void close() throws SQLException {
- DataSourceUtils.releaseConnection(this.connection, this.dataSource);
- }
- }
如果开启MyBatis事务管理,则需要手动进行事务提交,否则事务会回滚到原状态;
String resource = "mybatis/config.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
User user = new User();
user.setName("liuliu");
user.setPassword("123123");
user.setScore("88");
String statement = "mybatis.mapping.UserMapper.insertUser";
session.insert(statement,user);
session.close();
如果在具体操作执行完后不通过sqlSession.commit()方法提交事务,事务在sqlSession关闭时会自动回滚到原状态;只有执行了commit()事务提交方法才会真正完成操作;
如果不执行sqlSession.commit()操作,直接执行sqlSession.close(),则会在close()中进行事务回滚;
如果不执行sqlSession.commit()操作也不手动关闭sqlSession,在程序结束时关闭数据库连接时会进行事务回滚;
String resource = "mybatis/config.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
User user = new User();
user.setName("liuliu");
user.setPassword("123123");
user.setScore("88");
String statement = "mybatis.mapping.UserMapper.insertUser";
session.insert(statement,user);
session.commit();
session.close();
在XML配置文件中定义事务工厂类型,JDBC或者MANAGED分别对应JdbcTransactionFactory.class和ManagedTransactionFactory.class;
如果type=”JDBC”则使用JdbcTransactionFactory事务工厂则MyBatis独立管理事务,直接使用JDK提供的JDBC来管理事务的各个环节:提交、回滚、关闭等操作;
如果type=”MANAGED”则使用ManagedTransactionFactory事务工厂则MyBatis不在ORM层管理事务而是将事务管理托付给其他框架,如Spring;
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" /> //相当于<transactionManager type="JdbcTransactionFactory.class" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="BIUBIU" />
</dataSource>
</environment>
</environments>
在从SessionFactory中获取sqlSession时候会根据environment配置获取相应的事务工厂TransactionFactory,并从中获取事务实例当做参数传递给Executor,用来从中获取Connection数据库连接;
public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
getTransactionFactoryFromEnvironment()方法根据XML配置获取JdbcTransactionFactory或者ManagedTransactionFactory;ManagedTransactionFactory类中的commit()方法和rollback()方法都为空,事务相关操作不发挥作用;
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
MyBatis可以通过XML配置是否独立处理事务,可以选择不单独处理事务,将事务托管给其他上层框架如spring等;
如果MyBatis选择处理事务则事务会对数据库操作产生影响
对UPDATE操作的影响主要表现在UPDATE操作后如果没有进行事务提交则会子啊会话关闭时进行数据库回滚;
对SELECT操作的影响主要表现在二级缓存上,执行SELECT操作后如果未进行事务提交则缓存会被放在临时缓存中,后续的SELECT操作无法使用该缓存,直到进行commit()事务提交,临时缓存中的数据才会被转移到正式缓存中;
明天计划的事情:(一定要写非常细致的内容)
遇到的问题:(遇到什么困难,怎么解决的)
收获:(通过今天的学习,学到了什么知识)
评论