DataBaseDaoAbstract
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.slf4j.Logger; public abstract class DataBaseDaoAbstract<T> { private static Logger logger = CocoLoggerFactory.getLogger(DataBaseDaoAbstract.class); protected T execQueryObject(String sql, Object ...params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
if(result.next()) {
T t = this.parse(result);
return t;
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return null;
} protected T execQueryObject(String sql, Collection<Object> params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
if(result.next()) {
T t = this.parse(result);
return t;
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return null;
} protected <K> K execQueryObject(String sql, Class<K> clazz, Object ...params) throws Exception {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
if(result.next()) {
if(this.isSimpleClass(clazz)) {
return (K) this.getValue(result, clazz, 1);
}
K instance = clazz.newInstance();
Map<Integer, Method> columnMethodMap = this.generateMethodMap(clazz, result.getMetaData());
for(Entry<Integer, Method> entry : columnMethodMap.entrySet()) {
Object param = this.getValue(result, entry.getValue().getParameterTypes()[0], entry.getKey());
entry.getValue().invoke(instance, param);
}
return instance;
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return null;
}
protected <K> K execQueryObject(String sql, Class<K> clazz, Collection<Object> params) throws Exception {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
if(result.next()) {
if(this.isSimpleClass(clazz)) {
return (K) this.getValue(result, clazz, 1);
}
K instance = clazz.newInstance();
Map<Integer, Method> columnMethodMap = this.generateMethodMap(clazz, result.getMetaData());
for(Entry<Integer, Method> entry : columnMethodMap.entrySet()) {
Object param = this.getValue(result, entry.getValue().getParameterTypes()[0], entry.getKey());
entry.getValue().invoke(instance, param);
}
return instance;
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return null;
} protected <K> List<K> execQueryObjects(String sql, Class<K> clazz, Object ...params) throws Exception {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
List<K> returnList = Lists.newArrayList();
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
if(this.isSimpleClass(clazz)) {
while(result.next()) {
returnList.add((K) this.getValue(result, clazz, 1));
}
}
Map<Integer, Method> columnMethodMap = this.generateMethodMap(clazz, result.getMetaData());
while(result.next()) {
K instance = clazz.newInstance();
for(Entry<Integer, Method> entry : columnMethodMap.entrySet()) {
Object param = this.getValue(result, entry.getValue().getParameterTypes()[0], entry.getKey());
entry.getValue().invoke(instance, param);
}
returnList.add(instance);
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return returnList;
} protected <K> List<K> execQueryObjects(String sql, Class<K> clazz, Collection<Object> params) throws Exception {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
List<K> returnList = Lists.newArrayList();
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
if(this.isSimpleClass(clazz)) {
while(result.next()) {
returnList.add((K) this.getValue(result, clazz, 1));
}
}
Map<Integer, Method> columnMethodMap = this.generateMethodMap(clazz, result.getMetaData());
while(result.next()) {
K instance = clazz.newInstance();
for(Entry<Integer, Method> entry : columnMethodMap.entrySet()) {
Object param = this.getValue(result, entry.getValue().getParameterTypes()[0], entry.getKey());
entry.getValue().invoke(instance, param);
}
returnList.add(instance);
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return returnList;
} private boolean isSimpleClass(Class<?> clazz) {
if(clazz.isPrimitive()) {
return true;
}
if(clazz.equals(Integer.class) || clazz.equals(Long.class)
|| clazz.equals(Short.class) || clazz.equals(String.class)
|| clazz.equals(Float.class) || clazz.equals(Double.class)
|| clazz.equals(BigDecimal.class) || clazz.equals(Byte.class)
|| clazz.equals(Boolean.class) || Date.class.isAssignableFrom(clazz)) {
return true;
}
return false; } private Map<Integer, Method> generateMethodMap(Class<?> clazz, ResultSetMetaData metaData) throws SQLException {
Map<Integer, Method> columnMethodMap = Maps.newHashMap();
Map<String, Method> methodMap = Maps.newHashMap();
Method[] methods = clazz.getMethods();
for(int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
if(methodName.startsWith("set") && methods[i].getParameterTypes().length == 1) {
methodName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
methodMap.put(methodName, methods[i]);
}
}
for(int i = 1; i <= metaData.getColumnCount(); i++) {
Method method = methodMap.get(metaData.getColumnLabel(i));
if(method == null) {
continue;
}
columnMethodMap.put(i, method);
}
return columnMethodMap;
} private Object getValue(ResultSet result, Class<?> paramterType, int columnIndex) throws SQLException {
if(result.getObject(columnIndex) == null && !paramterType.isPrimitive()) {
return null;
}
if(paramterType.equals(int.class) || paramterType.equals(Integer.class)) {
return result.getInt(columnIndex);
}
if(paramterType.equals(long.class) || paramterType.equals(Long.class)) {
return result.getLong(columnIndex);
}
if(paramterType.equals(Byte.class) || paramterType.equals(byte.class)) {
return result.getByte(columnIndex);
}
if(paramterType.equals(Short.class) || paramterType.equals(short.class)) {
return result.getShort(columnIndex);
}
if(paramterType.equals(Boolean.class) || paramterType.equals(boolean.class)) {
return result.getBoolean(columnIndex);
}
if(paramterType.equals(Float.class) || paramterType.equals(float.class)) {
return result.getFloat(columnIndex);
}
if(paramterType.equals(Double.class) || paramterType.equals(double.class)) {
return result.getDouble(columnIndex);
}
if(paramterType.equals(BigDecimal.class)) {
return result.getBigDecimal(columnIndex);
}
return result.getObject(columnIndex);
} private void addParamters(PreparedStatement stmm, Object ...params) throws SQLException {
if(params != null && params.length != 0) {
int i = 1;
for(Object param : params) {
if(param instanceof Integer) {
stmm.setInt(i, (Integer)param);
} else if (param instanceof Long) {
stmm.setLong(i, (Long)param);
} else if (param instanceof Byte) {
stmm.setByte(i, (Byte)param);
} else if (param instanceof Boolean) {
stmm.setBoolean(i, (Boolean)param);
} else if (param instanceof String) {
stmm.setString(i, (String) param);
} else if(param instanceof Short) {
stmm.setShort(i, (Short) param);
} else {
stmm.setObject(i, param);
}
i ++;
}
}
}
private void addParamters(PreparedStatement stmm, Collection<Object> params) throws SQLException {
if(params != null && params.size() != 0) {
int i = 1;
for(Object param : params) {
if(param instanceof Integer) {
stmm.setInt(i, (Integer)param);
} else if (param instanceof Long) {
stmm.setLong(i, (Long)param);
} else if (param instanceof Byte) {
stmm.setByte(i, (Byte)param);
} else if (param instanceof Boolean) {
stmm.setBoolean(i, (Boolean)param);
} else if (param instanceof String) {
stmm.setString(i, (String) param);
} else if(param instanceof Short) {
stmm.setShort(i, (Short) param);
} else {
stmm.setObject(i, param);
}
i ++;
}
}
} protected List<T> execQueryObjects(String sql, Object ...params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
List<T> returnList = Lists.newArrayList();
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
while(result.next()) {
T t = this.parse(result);
returnList.add(t);
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return returnList;
} protected List<T> execQueryObjects(String sql, Collection<Object> params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
List<T> returnList = Lists.newArrayList();
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
while(result.next()) {
T t = this.parse(result);
returnList.add(t);
}
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
return returnList;
} protected int execInsert(String sql, Object ...params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
return stmm.executeUpdate();
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execInsert(String sql, Collection<Object> params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
return stmm.executeUpdate();
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execInsertReturnId(String sql, String name, Object object, Object ...params ) throws Exception {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
int effectRows = stmm.executeUpdate();
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method[] methods = object.getClass().getMethods();
Method methodInvoke = null;
for(Method method : methods) {
if(method.getName().equals(methodName)) {
methodInvoke = method;
}
}
if(methodInvoke != null) {
Object id = this.getConnectionId(connection, methodInvoke.getParameterTypes()[0]);
methodInvoke.invoke(object, id);
}
return effectRows;
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execInsertReturnId(String sql, String name, Object object, Collection<Object> params ) throws Exception {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
int effectRows = stmm.executeUpdate();
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method[] methods = object.getClass().getMethods();
Method methodInvoke = null;
for(Method method : methods) {
if(method.getName().equals(methodName)) {
methodInvoke = method;
}
}
if(methodInvoke != null) {
Object id = this.getConnectionId(connection, methodInvoke.getParameterTypes()[0]);
methodInvoke.invoke(object, id);
}
return effectRows;
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execUpdate(String sql, Object ...params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
return stmm.executeUpdate();
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execUpdate(String sql, Collection<Object> params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
return stmm.executeUpdate();
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execDelete(String sql, Object ...params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
return stmm.executeUpdate();
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int execDelete(String sql, Collection<Object> params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
return stmm.executeUpdate();
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int selectCount(String sql, Object ...params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
result.next();
return result.getInt(1);
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} protected int selectCount(String sql, Collection<Object> params) throws SQLException {
PooledDatabaseConnection connection = this.getConnection();
PreparedStatement stmm = null;
try {
stmm = connection.prepareStatement(sql);
this.addParamters(stmm, params);
ResultSet result = stmm.executeQuery();
result.next();
return result.getInt(1);
} finally {
DBUtil.close(stmm);
if(TransactionContainer2.needAutoCommit()) {
connection.pushConnection();
}
}
} private PooledDatabaseConnection getConnection() {
PooledDatabaseConnection connection = TransactionContainer2.getConnection();
if(connection != null) {
return connection;
} DataSourceConnection dataSource = this.getClass().getAnnotation(DataSourceConnection.class);
if(dataSource == null) {
throw new RuntimeException(this.getClass().getSimpleName() + " do not has Connection Conf");
}
Class<? extends IConnectionConfiguration> connectionConf = dataSource.connection();
connection = DatabaseConnectionPool.getPooledConnection(connectionConf);
if(connection == null) {
throw new RuntimeException("can not get db connection");
} if(!TransactionContainer2.needAutoCommit()) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
TransactionContainer2.setConnection(connection);
}
return connection;
} private Object getConnectionId(PooledDatabaseConnection conn, Class<?> type) throws SQLException {
String idQuery = "select @@Identity";
PreparedStatement idQuerySttmt = conn.prepareStatement(idQuery);
try {
ResultSet idQueryRs = idQuerySttmt.executeQuery();
idQueryRs.next();
return getValue(idQueryRs, type, 1);
} finally {
DBUtil.close(idQuerySttmt);
} } protected abstract T parse(ResultSet result) throws SQLException;
}
DataBaseDaoAbstract的更多相关文章
随机推荐
- HTTP rfc是什么及其工作过程
概念: HTTP协议描述的是发送方与接收方的通信协议,通过两方的自觉遵守而存在,HTTP是运行于应用层的协议,基于TCP协议而运作.基本上是客户/服务器对答模式,其中也包括在传输过程中的代理,网关,通 ...
- zabbix3.4.7官方解释触发器
函数 描述 参数 说明 abschange 最近获取值与之前获取值差的绝对值. 支持值的类型: float, int, str, text, log 例如: (最近获取值;之前获取值=ab ...
- 关于win10安装javaJDK时遇到的问题
昨天晚上装了一下javaJDK1.8,在安装成功并且按照教程设置完环境变量之后进入了cmd界面,输入java,java -version都正常显示,但是输入javac却报错:javac不是内部或外部命 ...
- 健壮程序之--SQL优化
(仅为自己以后快速参考!!!) (1)防止数据库字段为空 解决方案(1):DECODE() DECODE(JN.USERID, , '待聘', UI.USERNAME) USERNAME, 解决方案( ...
- JVM Optimization
架构图 基本概念说明 堆(heap):数据存储,对象实例:空间往上增长,线程共享区:大小可通过-Xmx和-Xms配置 新生代(Young Generation):划分为Eden Space和两个Sur ...
- Java语法基础学习DaySeventeen(多线程续)
一.线程的特点 1.线程的分类 java中的线程分为两类:守护线程和用户线程.唯一的区别是判断JVM何时离开. 守护线程是用来服务用户线程的,通过在start()方法前调用Thread.setDaem ...
- disjoint set
MAKE-SET.x/ creates a new set whose only member (and thus representative) is x. Since the sets are d ...
- laravel 常用命令
1.创建控制器 php artisan make:controller ArticleController // 带 restful 风格 php artisan make:controller Ar ...
- Java错误:结束的字符文字
编译器为NetBeans 在学习java的时候突然出现了以下错误 错误代码是: Gen <Integer ,String> a = new Gen <Integer, String& ...
- phpcms 加载微信类库,生成签名
在phpcms 中 pc_base:load_config(文件名) 用于加载配置文件,配置文件存放于phpcms目录下的caches/configs中 在控制器新增加载微信类库的方法: /** * ...