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. 深入学习c++--多线程编程(一)

    1. 简介 2. 线程使用 2.1 demo #include <iostream> #include <thread> #include <future> usi ...

  2. LeetCode_401. Binary Watch

    401. Binary Watch Easy A binary watch has 4 LEDs on the top which represent the hours (0-11), and th ...

  3. 09点睛Spring4.1-AOP

    9.1 AOP AOP可以了让一组类共享相同的行为.在OOP中只能通过继承类和实现接口,这样使代码的耦合度增强,且类继承只能为单继承,阻碍更多行为添加到一组类上; 下面演示一个日志系统的实现,简单但不 ...

  4. C# .NET WINFORM MUTEX 互斥

    static class Program 里的全局变量: static System.Threading.Mutex appMutex; Main 方法里的内容: string exeName = & ...

  5. Django 高级视图

    一.Django限制请求method 常用的请求method: GET请求:GET请求一般用来向服务器索取数据,但不会向服务器提交数据,不会对服务器的状态进行更改.比如向服务器获取某篇文章的详情. P ...

  6. 【剑指offer】面试题 25. 合并两个排序的链表

    面试题 25. 合并两个排序的链表 NowCoder 题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则. Java 实现 ListNode Clas ...

  7. [转帖]04-创建kubeconfig认证文件

    04-创建kubeconfig认证文件 https://www.cnblogs.com/guigujun/p/8366530.html 学习一下 貌似挺有用的. 本文档记录自己的学习历程! 创建 ku ...

  8. mysql常用系统函数归类

    数学函数 函数 作用 ABS(x) 返回x的绝对值 BIN(x) 返回x的二进制(OCT返回八进制,HEX返回十六进制) EXP(x) 返回值e(自然对数的底)的x次方 GREATEST(x1,x2, ...

  9. Windows Subsystem for Linux(wsl)使用

    由于项目有一些环境需要在linux环境运行.可用微软win10的WSL来搭配使用 安装wsl 控制面板--程序和功能--启用或关闭windows功能,适用于linux的windows系统 应用商城下载 ...

  10. MySQL中的case when 中对于NULL值判断的坑

    sql中的case when 有点类似于Java中的switch语句,比较灵活,但是在Mysql中对于Null的处理有点特殊 Mysql中case when语法: 语法1: CASE case_val ...