[TOC]
代码高亮
java
/*
* Copyright 2010-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring;
import static org.springframework.util.Assert.notNull;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Handles MyBatis SqlSession life cycle. It can register and get SqlSessions from Spring
* {@code TransactionSynchronizationManager}. Also works if no transaction is active.
*
* @author Hunter Presnall
* @author Eduardo Macarron
*/
public final class SqlSessionUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionUtils.class);
private static final String NO_EXECUTOR_TYPE_SPECIFIED = "No ExecutorType specified";
private static final String NO_SQL_SESSION_FACTORY_SPECIFIED = "No SqlSessionFactory specified";
private static final String NO_SQL_SESSION_SPECIFIED = "No SqlSession specified";
/**
* This class can't be instantiated, exposes static utility methods only.
*/
private SqlSessionUtils() {
// do nothing
}
/**
* Creates a new MyBatis {@code SqlSession} from the {@code SqlSessionFactory} provided as a parameter and using its
* {@code DataSource} and {@code ExecutorType}
*
* @param sessionFactory
* a MyBatis {@code SqlSessionFactory} to create new sessions
*
* @return a MyBatis {@code SqlSession}
*
* @throws TransientDataAccessResourceException
* if a transaction is active and the {@code SqlSessionFactory} is not using a
* {@code SpringManagedTransactionFactory}
*/
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory) {
ExecutorType executorType = sessionFactory.getConfiguration().getDefaultExecutorType();
return getSqlSession(sessionFactory, executorType, null);
}
}
近期评论