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的更多相关文章
随机推荐
- 记一下JavaScript的几种排序算法
零.写在最前 排序的方法有很多种,这篇文章只是记录我熟悉的算法: 我发现了一个关于排序算法很有趣的网站,把相关的算法演示做成了动画,有兴趣的同学可以看看! 附上SortAnimate网站链接:http ...
- tensoFlow之DNN文本分类
TensorFlow文本分类: 亲测可用:https://blog.csdn.net/u012052268/article/details/77862202 简单实例:https://www.leip ...
- 厨娘ui设计文档
厨娘ui设计文档 一.概述 中国的饮食文化从古到今源远流长.在生活日益丰富的今天,人们对饮食的要求不仅仅是温饱,更讲究健康和美味.近年来,饮食甚至成为娱乐的一部分,关于吃的流行用语层出不穷,可见在当今 ...
- 指导手册04:运行MapReduce
指导手册04:运行MapReduce Part 1:运行单个MapReduce任务 情景描述: 本次任务要求对HDFS目录中的数据文件/user/root/email_log.txt进行计算处理, ...
- python基础——元组
元组运算符 与字符串一样,元组之间可以使用 + 号和 * 号进行运算.这就意味着他们可以组合和复制,运算后会生成一个新的元组. Python 表达式 结果 描述 len((1, 2, 3)) 3 计算 ...
- 外网如何访问web项目holer实现篇
外网访问WEB 内网主机上安装了WEB服务器,只能在局域网内访问,怎样从公网也能访问本地WEB应用? 本文将介绍使用holer实现的具体步骤. 1. 准备工作 1.1 安装Java 1.7及以上版本 ...
- scrapy中crawlspide中callback和follow函数的作用及使用方法
Rule(LinkExtractor(allow=r'i/tems'),callback='parse_item',follow=True) 当前代码的含义就是将当前页面及按照allow=r'i/t ...
- scrapy初探(一)-斗鱼TV直播信息抓取
由于有相关需求,最近两天开始学了一下scrapy 这次我们就以爬取斗鱼直播间为例,我们准备爬取斗鱼所有的在线直播信息, 包括1.主播昵称 2.直播领域 3.所在页面数 4.直播观看人数 5.直播间ur ...
- Ubuntu16.04 安装 MySQL
本篇介绍如何在Ubuntu系统上安装MySQL数据库,以及介绍数据库的基本命令. 一.下载和安装MySQL 可以通过apt-get下载并安装 sudo apt-get install mysql-se ...
- 神州数码OSPF基于区域认证(简单、MD5认证)
实验要求:掌握基于区域的简单认证及MD5认证 拓扑如下 简单认证 R1 enable 进入特权模式 config 进入全局模式 hostname R1 修改名称 interface l0 进入端口 i ...