jetbrick.dao.orm.utils.PreparedStatementCreator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jetbrick-orm Show documentation
Show all versions of jetbrick-orm Show documentation
Object-relational mapping framework for jetbrick
/**
* Copyright 2013-2014 Guoqiang Chen, Shanghai, China. All rights reserved.
*
* Email: [email protected]
* URL: http://subchen.github.io/
*
* 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 jetbrick.dao.orm.utils;
import java.sql.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jetbrick.beans.ClassUtils;
import jetbrick.collections.iterators.ArrayIterator;
import jetbrick.lang.StringUtils;
import jetbrick.reflect.BeanMap;
public class PreparedStatementCreator {
private static final Pattern namedParameterPattern = Pattern.compile("\\:([a-zA-Z0-9_]+)");
@SuppressWarnings("unchecked")
public static PreparedStatement createPreparedStatement(Connection conn, String sql, Object... parameters) throws SQLException {
if (parameters == null) {
return createByIterator(conn, sql, null);
}
if (parameters.length == 1) {
Object value = parameters[0];
Class> clazz = value.getClass();
if (ClassUtils.isAssignable(clazz, Map.class)) {
return createByMap(conn, sql, (Map) value);
} else if (ClassUtils.isAssignable(clazz, Collection.class)) {
return createByIterator(conn, sql, new ArrayIterator(parameters));
} else if (clazz.isPrimitive() || clazz.getName().startsWith("java.")) {
return createByIterator(conn, sql, new ArrayIterator(parameters));
} else {
Map beanMap = new BeanMap(value);
return createByMap(conn, sql, beanMap);
}
} else {
return createByIterator(conn, sql, new ArrayIterator(parameters));
}
}
/**
* Support ? as parameter
*/
protected static PreparedStatement createByIterator(Connection conn, String sql, Iterator> parameters) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql);
if (parameters != null) {
int index = 1;
while (parameters.hasNext()) {
Object parameter = parameters.next();
if (parameter == null) {
ps.setObject(index, null);
} else {
ps.setObject(index, parameter);
}
index++;
}
}
return ps;
}
/**
* Support :name as parameter, and Array or Collection type
*/
protected static PreparedStatement createByMap(Connection conn, String sql, Map parameters) throws SQLException {
StringBuffer sb = new StringBuffer();
List