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的更多相关文章

随机推荐

  1. java基础---->Serializable的使用

    本次讲解中我们建立一个Java的项目去体会一下序列化Serializable的使用,序列化的原理以及序列化的自定义请参见我的另外一篇博客(java高级---->Serializable序列化的源 ...

  2. Python Flask框架

    Python有很多Web框架,可谓是百家争鸣,我这里列出几个比较叼的几个框架 Django      市场占有率最高,官方文档几近完美,但是适合比较大的项目,小项目会显得累赘. Tornado    ...

  3. Weka中数据挖掘与机器学习系列之Weka系统安装(四)

    能来看我这篇博客的朋友,想必大家都知道,Weka采用Java编写的,因此,具有Java“一次编译,到处运行”的特性.支持的操作系统有Windows x86.Windows x64.Mac OS X.L ...

  4. Eclipse导入war包二次开发

    有实际项目在跑的war包,却没有源码,苦于想查看源码,身处运维组为研发组看不起,拿不到源码,只能自己来反编译了. 其实在解压war包后,可以看到文件夹中,已经存在了jsp文件,但是却没有逻辑代码层(a ...

  5. 安装软件碰见error2502 2503

    把鼠标放到Win8屏幕的最左下角,等待Win8 Metro界面的缩略图出现后点击鼠标右键,在弹出的菜单中选择“命令提示符(管理员)”   打开的“命令提示符(管理员)”   找到自己将要安装的程序路径 ...

  6. JAVA002标识符的命名规则、关键字

    标志符命名规则: 1.标志符可以由字母.数字.下划线(_)和美元符号($)组成,不能以数字开头($sen.Void) 2.标志符严格区分大小写 3.标志符不能是Java的关键字和保留字(eg:publ ...

  7. Qthread的使用方法

    1:重载 run()函数 2:将对象移到Qthread对象中 Movetothread 该方法必须通过信号 -槽来激发.

  8. Windows安装Anaconda出现failed to create menus

    当出现上述问题时,有以下的解决办法: (1)默认安装,即一直next: (2)安装路径里不要包含英文以外的语言,即安装路径全部用英文命名: (3)先不要安装python,或者将安装的python配置好 ...

  9. Linux第一节课学习笔记

    我的目标是考过RHCE 开源软件有使用.复制.传播.收费.修改及创建衍生品自由,其中后二者只有开源软件才有,前四者开闭源共有.

  10. spring-boot入门总结

    1.org.springframework.web.bind.annotation不存在 错误的pom.xml <dependency> <groupId>org.spring ...