package com.me.dbComponent;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function; /**
* Created by zgj on 2017/7/27.
*/
public abstract class DbTemplate { private <T> T execute(Function<Connection, T> function) {
Connection connection = getConnection();
try {
return function.apply(connection);
} finally {
releaseConnection(connection);
}
} protected void releaseConnection(Connection connection) {
throw new RuntimeException("the method releaseConnection not implements");
} protected Connection getConnection() {
throw new RuntimeException("the method getConnection not implements");
} public int insert(String sql, Object... args) {
return insert(sql, preparedStatement -> setParameter(preparedStatement, args));
} public int insert(String sql, Iterable<?> args) {
return insert(sql, preparedStatement -> setParameter(preparedStatement, args));
} public int insert(String sql, Map<String, Object> args) {
return insert(sql, preparedStatement -> setParameter(preparedStatement, args));
} private int insert(String sql, Consumer<PreparedStatement> statementSetter) {
return execute(connection -> {
try (PreparedStatement pst = connection.prepareStatement(sql)) {
connection.setAutoCommit(false);
if (statementSetter != null) {
statementSetter.accept(pst);
}
int count = pst.executeUpdate();
connection.commit();
return count;
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException e1) {
throw new RuntimeException("transaction rollback occurred exception", e);
}
throw new RuntimeException(e);
}
}); } public <T> T queryObject(String sql , Function<ResultSet, T> resultSet, Object... args) {
return (T)query(sql, preparedStatement -> setParameter(preparedStatement, args), resultSet);
} private <T> T query(String sql, Consumer<PreparedStatement> consumer, Function<ResultSet, T> resultSetExtractor) {
return execute(connection -> {
try (PreparedStatement pst = connection.prepareStatement(sql)) {
if (consumer != null) {
consumer.accept(pst);
}
try (ResultSet resultSet = pst.executeQuery()) {
return resultSetExtractor.apply(resultSet);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}); } public <T> T queryObject(String sql, Object... args) {
return (T)query(sql, preparedStatement -> setParameter(preparedStatement, args), DbTemplate::toOne);
} private <T> List<T> queryList(String sql, Consumer<PreparedStatement> statementConsumer, Function<ResultSet, T> rowMapper) {
return query(sql, statementConsumer, resultSet -> {
try {
int size = getRowSize(resultSet);
if (size == 0)
return Collections.<T>emptyList();
List<T> list = new ArrayList<>();
while (resultSet.next()) {
T t = rowMapper.apply(resultSet);
if (!Objects.isNull(t)) {
list.add(t);
}
}
return list;
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
} public <T> List<T> queryList(String sql, Object[] args, Function<ResultSet, T> rowMapper) {
return queryList(sql, preparedStatement -> setParameter(preparedStatement, args), rowMapper);
} public long queryCount(String sql) {
return queryCount(sql, "");
} public long queryCount(String sql, Object... args) {
Number number = queryObject(sql,args);
return number == null ? 0L : number.longValue();
} public boolean isExist(String sql) {
return isExist(sql, "");
} public boolean isExist(String sql, Object... args) {
long count = queryCount(sql, args);
return count > 0L;
} private static Object toOne(ResultSet resultSet) {
if (getRowSize(resultSet) > 1) {
throw new RuntimeException("the result set is more than 1 row");
}
try {
int colAmount = resultSet.getMetaData().getColumnCount();
if (colAmount == 1 && resultSet.next()) {
return resultSet.getObject(1);
} else if (colAmount > 1 && resultSet.next()) {
Object[] temp = new Object[colAmount];
for (int i = 0; i < colAmount; i++) {
temp[i] = resultSet.getObject(i + 1);
}
return temp;
}
return null;
} catch (SQLException e) {
throw new RuntimeException(e);
}
} private static int getRowSize(ResultSet resultSet) {
int rows = 0;
try {
if (resultSet.last()) {
rows = resultSet.getRow();
resultSet.beforeFirst();
}
return rows;
} catch (SQLException e) {
throw new RuntimeException(e);
}
} private static void setParameter(PreparedStatement preparedStatement, Object[] args) {
if (args == null || args.length == 0) {
return;
}
try {
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} } private static void setParameter(PreparedStatement preparedStatement, Iterable<?> args) {
if (args == null) {
return;
}
int index = 0;
try {
for (Iterator i = args.iterator(); i.hasNext(); ) {
preparedStatement.setObject(++index, i.next());
}
} catch (SQLException e) {
throw new RuntimeException(e);
} } private static void setParameter(PreparedStatement preparedStatement, Map<String, Object> map) {
if (map == null) {
return;
}
int index = 0;
try {
for (String key : map.keySet()) {
preparedStatement.setObject(++index, map.get(key));
}
} catch (SQLException e) {
throw new RuntimeException(e);
} } }

DbTemplate的更多相关文章

  1. Mybatis3 框架理解

    最近工作比较闲,维护一个政府机关的短信发送平台,大部分业务逻辑都在Oracle数据库上,但自己明明应聘的是Java开发啊!!!整天写存储过程的我还是有一颗写高级语言的心啊!!!好吧!!!先找个数据库方 ...

  2. 好久不见,Java设计模式

    引子 设计模式是很多程序员总结出来的最佳实践.曾经在刚开始写项目的时候学习过设计模式,在开发过程中,也主动或者被动的使用过.现在写代码虽说不会特意明确在用哪种设计模式,但潜移默化的写出来公认的最佳实践 ...

随机推荐

  1. Web.Config中配置字符串含引号的处理

    配置文件中往往要用到一些特殊的字符, Web.Config默认编码格式为UTF-8,对于XML文件,要用到实体转义码来替换.对应关系如下: 字符 转义码 & 符号 & & 单引 ...

  2. 内存检测工具valgrind的安装和简单使用

    1. 安装 .tar.bz2 cd valgrind- sudo ./configure sudo make sudo make install 2. 简单使用 #include <stdio. ...

  3. delphi 多线程定时执行程序如何写

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  4. SpringCloud学习笔记:服务支撑组件

    SpringCloud学习笔记:服务支撑组件 服务支撑组件 在微服务的演进过程中,为了最大化利用微服务的优势,保障系统的高可用性,需要通过一些服务支撑组件来协助服务间有效的协作.各个服务支撑组件的原理 ...

  5. RobotFramework: 获取当前时间戳

    robot中先导入DateTime库 #获取当前时间:2019-07-31 10:46:29.940 ${time} Get Current Date result_format=timestamp ...

  6. pv回收

    学习cloudman中的k8s 152课,创建pod时,需要在k8s-host2 中挂着到在k8s-master 中/nfs中创建的挂载目录,结果提示没有/nfs/pv1 root@k8s-maste ...

  7. Generative Adversarial Network (GAN) - Pytorch版

    import os import torch import torchvision import torch.nn as nn from torchvision import transforms f ...

  8. 022 Android .9图片的含义及制作教程

    1.图片(.9.png格式)的概念 (1)9patch图片是andriod app开发里一种特殊的图片形式,文件的扩展名为:.9.png (2)9patch图片的作用就是在图片拉伸的时候保证其不会失真 ...

  9. visio 绘图素材

    1. 前言 visio是个绘图的好工具,可是自带图形元素有限,没有还要自己画. 推荐几个矢量图形素材库,里边有很多图形,很方便的导入到visio中,放大也不失真. 阿里巴巴矢量图库网 stockio ...

  10. go 食用指南

    Golang高效食用秘籍 一.关于构建 1.1 go环境变量 $ go env // 查看go 的环境变量 其中 GOROOT 是golang 的安装路径 GOPATH 是go命令依赖的一个环境变量 ...