cn.coder.jdbc.session.BaseSqlSession Maven / Gradle / Ivy
package cn.coder.jdbc.session;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.coder.jdbc.SqlSession;
import cn.coder.jdbc.SqlTranction;
import cn.coder.jdbc.core.DataSourceConfig;
import cn.coder.jdbc.core.JdbcDataSource;
import cn.coder.jdbc.support.ResultMapper;
import cn.coder.jdbc.util.JdbcUtils;
public abstract class BaseSqlSession implements SqlSession {
private static final Logger logger = LoggerFactory.getLogger(BaseSqlSession.class);
private final DataSource ds;
private final ThreadLocal tl = new ThreadLocal<>();
private static final SqlTranction[] EMPTY_ARRAY = new SqlTranction[0];
protected BaseSqlSession(DataSource dataSource) {
this.ds = dataSource;
}
public SqlTranction beginTranction() throws Exception {
return beginTranction(EMPTY_ARRAY);
}
public SqlTranction beginTranction(SqlTranction... tranctions) throws Exception {
if (tl.get() != null)
throw new RuntimeException("The tranction has already exist");
SqlTranction tran = new DefaultSqlTranction(this, ds.getConnection(), tranctions);
tl.set(tran);
logger.debug("Begin tranction:{}", tran.hashCode());
return tran;
}
public void endTranction(SqlTranction tran) {
logger.debug("End tranction:{}", tran.hashCode());
tl.remove();
}
protected T doExecute(ResultMapper mapper) {
SqlTranction tran = tl.get();
Connection conn = null;
Statement stmt = null;
try {
if (tran == null) {
conn = ds.getConnection();
} else {
if (logger.isDebugEnabled())
logger.debug("Run with tranction:{}", tran.hashCode());
conn = tran.Connection();
}
stmt = mapper.makeStatement(conn);
applySettings(stmt);
T result = mapper.doStatement(stmt);
handleWarnings(stmt);
return result;
} catch (SQLException ex) {
if (stmt != null)
logger.error("Error:[" + stmt.toString() + "]", ex);
throw new RuntimeException("Execute faild:", ex);
} finally {
JdbcUtils.closeStatement(stmt);
if (tran == null) {
JdbcUtils.closeConnection(conn);
}
}
}
private void applySettings(Statement stmt) throws SQLException {
// stmt.setMaxRows(10);
if (this.ds instanceof JdbcDataSource) {
DataSourceConfig config = ((JdbcDataSource) this.ds).getConfig();
stmt.setQueryTimeout(config.getQueryTimeout());
}
}
private void handleWarnings(Statement stmt) throws SQLException {
// Do Nothing
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy