Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright 2016 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
*
* http://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 com.github.drinkjava2.jdbpro;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.dbutils.OutParameter;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.github.drinkjava2.jdbpro.template.SqlTemplateEngine;
/**
* DbPro is the enhanced version of Apache Commons DbUtils's QueryRunner, add
* below improvements:
*
*
* 1)Use ConnectionManager to manage connection for better transaction support
* 2)normal style methods but no longer throw SQLException, methods named as nXxxxx() format
* 3)In-line style methods, methods named as iXxxxx() format
* 4)SQL Template style methods, methods named as tXxxxx() format
*
*
* @author Yong Zhu
* @since 1.7.0
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class DbPro extends ImprovedQueryRunner implements NormalJdbcTool {// NOSONAR
public DbPro() {
super();
}
public DbPro(DataSource ds) {
super(ds);
}
public DbPro(DbProConfig config) {
super();
this.connectionManager = config.getConnectionManager();
this.sqlTemplateEngine = config.getTemplateEngine();
this.allowShowSQL = config.getAllowSqlSql();
this.logger = config.getLogger();
this.batchSize = config.getBatchSize();
this.sqlHandlers = config.getSqlHandlers();
this.iocTool = config.getIocTool();
this.slaves = config.getSlaves();
this.masters = config.getMasters();
this.masterSlaveOption = config.getMasterSlaveSelect();
this.specialSqlItemPreparers = config.getSpecialSqlItemPreparers();
}
public DbPro(DataSource ds, DbProConfig config) {
super(ds);
this.connectionManager = config.getConnectionManager();
this.sqlTemplateEngine = config.getTemplateEngine();
this.allowShowSQL = config.getAllowSqlSql();
this.logger = config.getLogger();
this.batchSize = config.getBatchSize();
this.sqlHandlers = config.getSqlHandlers();
this.iocTool = config.getIocTool();
this.slaves = config.getSlaves();
this.masters = config.getMasters();
this.masterSlaveOption = config.getMasterSlaveSelect();
this.specialSqlItemPreparers = config.getSpecialSqlItemPreparers();
}
/**
* Quite execute a SQL, do not throw any exception, if any exception happen,
* return -1
*/
public int quiteExecute(String sql, Object... params) {
try {
return execute(sql, params);
} catch (Exception e) {
return -1;
}
}
public void ________prepareMethods________() {// NOSONAR
}
/**
* Prepare a PreparedSQL for iXxxx (Single SQL) style, unknown objects (include
* null) will automatically looked as SQL pieces, more detail see doPrepare
* method
*/
public PreparedSQL iPrepare(Object... items) {
return doPrepare(true, items);
}
/**
* Prepare a PreparedSQL for pXxxx (Single SQL) style, pXxxx style only allow
* single String (The first appeared) as SQL, unknown objects (include null)
* will automatically looked as SQL parameters, more detail see doPrepare method
*/
public PreparedSQL pPrepare(Object... items) {
return doPrepare(false, items);
}
/**
* Prepare a PreparedSQL for iXxxx (In-line) style or pXxxx style, For iXxxx
* style, unknown items be treated as String, SQL parameters must written in
* param() method, for example:
*
* ctx.iQuery(new SimpleCacheHandler(), connection, "select u.** from users u
* where u.age>?", param(20)," and u.id=?", param("001"), MapListHandler.class);
*
*
* pXxxx style only allow first appeared String as SQL, left unknown items will
* be treated as SQL parameters, for example:
*
* ctx.pQuery(MapListHandler.class, "select * from users where age>? and id=?",
* 20 , "001" , connection, new PaginHandler(2,5), sql(" and name=?"), "Tom" );
*
* In above examples connection and sqlHandlers are optional items, these
* optional items can appear at anywhere
*
* @param items
* SQL String / SQL Parameters / Connection / ResultSetHandler class
* or instance / SqlHandler class or instance
* @return a PreparedSQL instance
*/
private PreparedSQL doPrepare(boolean iXxxStyle, Object... items) {// NOSONAR
PreparedSQL ps = realDoPrepare(null, null, iXxxStyle, items);
ps.addGlobalAndThreadedHandlers(this);
return ps;
}
protected PreparedSQL realDoPrepare(PreparedSQL lastPreSql, StringBuilder lastSqlBuilder, boolean iXxxStyle, // NOSONAR
Object... items) {
if (items == null || items.length == 0)
throw new DbProRuntimeException("prepareSQL items can not be empty");
PreparedSQL predSQL = lastPreSql;
if (predSQL == null)
predSQL = new PreparedSQL();
StringBuilder sql = lastSqlBuilder;
if (sql == null)
sql = new StringBuilder();
for (Object item : items) {
if (item == null) {
if (iXxxStyle)
throw new DbProRuntimeException("In iXxxx style, null value can not append as SQL piece");
else
predSQL.addParam(null);
} else if (!dealItem(iXxxStyle, predSQL, sql, item)) {
if (item instanceof SqlItem)
throw new DbProRuntimeException(
"One SqlItem did not find explainer, type=" + ((SqlItem) item).getType());
if (item.getClass().isArray()) {
realDoPrepare(predSQL, sql, iXxxStyle, (Object[]) item);
} else if (iXxxStyle)
sql.append(item); // iXxxx style, unknown is SQL piece
else
predSQL.addParam(item); // pXxxx style, unknown is parameter
}
}
predSQL.setSql(sql.toString());
return predSQL;
}
/**
* Here deal a non-null items, if can analyse it, return true, otherwise return
* false, subclass (like SqlBoxContext) can override this method to deal more
* trick.
*/
protected boolean dealItem(boolean iXxxStyle, PreparedSQL predSQL, StringBuilder sql, Object item) {// NOSONAR
if (item instanceof String) {
if (iXxxStyle)
sql.append(item);
else if (sql.length() > 0)
predSQL.addParam(item);
else
sql.append(item);
} else if (item instanceof PreparedSQL) {
PreparedSQL psItem = (PreparedSQL) item;
if (psItem.getSql() != null)
sql.append(psItem.getSql());
if (psItem.getParams() != null)
for (Object obj : psItem.getParams())
predSQL.addParam(obj);
} else if (item instanceof SqlTemplateEngine) {
predSQL.setTemplateEngine((SqlTemplateEngine) item);
} else if (item instanceof Map, ?>) {
predSQL.addTemplateMap((Map) item);
} else if (item instanceof SqlOption) {
if (SqlOption.USE_MASTER.equals(item)) {
predSQL.setMasterSlaveOption(SqlOption.USE_MASTER);
} else if (SqlOption.USE_SLAVE.equals(item)) {
predSQL.setMasterSlaveOption(SqlOption.USE_SLAVE);
} else if (SqlOption.USE_AUTO.equals(item)) {
predSQL.setMasterSlaveOption(SqlOption.USE_AUTO);
} else if (SqlOption.USE_BOTH.equals(item)) {
predSQL.setMasterSlaveOption(SqlOption.USE_BOTH);
} else if (SqlOption.USE_TEMPLATE.equals(item)) {
predSQL.setUseTemplate(true);
} else if (SqlOption.EXECUTE.equals(item)) {
predSQL.setOperationType(SqlOption.EXECUTE);
} else if (SqlOption.UPDATE.equals(item)) {
predSQL.setOperationType(SqlOption.UPDATE);
} else if (SqlOption.QUERY.equals(item)) {
predSQL.setOperationType(SqlOption.QUERY);
} else if (SqlOption.INSERT.equals(item)) {
predSQL.setOperationType(SqlOption.INSERT);
} else
throw new DbProRuntimeException("Un-explained SqlOption:" + item);
} else if (item instanceof SqlItem) {
SqlItem sqItem = (SqlItem) item;
SqlOption sqlItemType = sqItem.getType();
if (SqlOption.IGNORE.equals(sqlItemType))
return true;// Always return true for IGNORE type
else if (SqlOption.PARAM.equals(sqlItemType)) {
for (Object pm : sqItem.getParameters())
predSQL.addParam(pm);
} else if (SqlOption.BIND.equals(sqlItemType)) {
predSQL.addTemplateParam(sqItem);
} else if (SqlOption.SQL.equals(sqlItemType)) {
for (Object pm : sqItem.getParameters())
sql.append(pm);
} else if (SqlOption.QUESTION_PARAM.equals(sqlItemType)) {
int i = 0;
for (Object pm : sqItem.getParameters()) {
predSQL.addParam(pm);
if (i > 0)
sql.append(",");
sql.append("?");
i++;
}
} else if (SqlOption.NOT_NULL.equals(sqlItemType)) {
Object[] args = sqItem.getParameters();
if (args.length < 2)
throw new DbProRuntimeException("NOT_NULL type SqlItem need at least 2 args");
if (args[args.length - 1] != null) {
for (int i = 0; i < args.length - 1; i++)
dealItem(true, predSQL, sql, args[i]);// in NOT_NULL type, force use i style
predSQL.addParam(args[args.length - 1]);
}
} else if (SqlOption.VALUES_QUESTIONS.equals(sqlItemType)) {
sql.append(" values(");
for (int i = 0; i < predSQL.getParamSize(); i++) {
if (i > 0)
sql.append(",");
sql.append("?");
}
sql.append(")");
} else if (SqlOption.ENABLE_HANDLERS.equals(sqlItemType)) {
predSQL.enableAllHandlers();
} else if (SqlOption.DISABLE_HANDLERS.equals(sqlItemType)) {
predSQL.disableHandlers((Object[]) sqItem.getParameters());
} else if (SqlOption.SWITCHTO.equals(sqlItemType)) {
predSQL.setSwitchTo((DbPro) sqItem.getParameters()[0]);
} else if (SqlOption.IOC.equals(sqlItemType)) {
if (this.getIocTool() == null)
throw new DbProRuntimeException(
"A IocTool setting required to deal an @Ioc or ioc() method, please read user manual.");
for (Object claz : sqItem.getParameters()) {
Object obj = this.getIocTool().getBean((Class) claz);
dealItem(iXxxStyle, predSQL, sql, obj);
}
} else
return false;
} else if (item instanceof Connection)
predSQL.setConnection((Connection) item);
else if (item instanceof DbPro)
predSQL.setSwitchTo((DbPro) item);
else if (item instanceof SqlHandler)
predSQL.addHandler((SqlHandler) item);
else if (item instanceof ResultSetHandler)
predSQL.setResultSetHandler((ResultSetHandler) item);
else if (item instanceof Class) {
throw new DbProRuntimeException("Found a sqlItem is class type :'" + item + "', currently is not allowed.");
} else if (item instanceof SpecialSqlItem) {
if (specialSqlItemPreparers == null || specialSqlItemPreparers.length == 0)
throw new DbProRuntimeException(
"SpecialSqlItem found but no specialSqlItemPreparers be set, please read user manual how to set SpecialSqlItemPreparers");
for (SpecialSqlItemPreparer spPreparer : specialSqlItemPreparers) {
if (spPreparer.doPrepare(predSQL, sql, (SpecialSqlItem) item))// find the first preparer
return true;
}
return false;
} else
return false;
return true;
}
// ============================================================================
public void ________iXxxxStyles________() {// NOSONAR
}
// ============================================================================
/**
* Executes the in-line style query statement
*
* @param inlineSQL
* the in-line style SQL
* @return An object generated by the handler.
*/
public T iQuery(Object... inlineSQL) {
PreparedSQL ps = iPrepare(inlineSQL);
ps.ifNullSetType(SqlOption.QUERY);
return (T) runPreparedSQL(ps);
}
/**
* Execute an In-line style query for an Object, only return the first row and
* first column's value if more than one column or more than 1 rows returned
*
* @param inlineSQL
* @param params
* @return An Object or null value determined by SQL content
*/
public T iQueryForObject(Object... inlineSQL) {
PreparedSQL ps = iPrepare(inlineSQL);
ps.ifNullSetType(SqlOption.QUERY);
if (ps.getResultSetHandler() == null)
ps.setResultSetHandler(new ScalarHandler(1));
return (T) runPreparedSQL(ps);
}
/**
* In-line style execute query and force return a long value, runtime exception
* may throw if result can not be cast to long.
*/
public long iQueryForLongValue(Object... inlineSQL) {
return ((Number) iQueryForObject(inlineSQL)).longValue();// NOSONAR
}
/**
* In-line style execute query and force return a String object.
*/
public String iQueryForString(Object... inlineSQL) {
return String.valueOf(iQueryForObject(inlineSQL));
}
/**
* In-Line style execute query and force return a List