DbTemplate
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的更多相关文章
- Mybatis3 框架理解
最近工作比较闲,维护一个政府机关的短信发送平台,大部分业务逻辑都在Oracle数据库上,但自己明明应聘的是Java开发啊!!!整天写存储过程的我还是有一颗写高级语言的心啊!!!好吧!!!先找个数据库方 ...
- 好久不见,Java设计模式
引子 设计模式是很多程序员总结出来的最佳实践.曾经在刚开始写项目的时候学习过设计模式,在开发过程中,也主动或者被动的使用过.现在写代码虽说不会特意明确在用哪种设计模式,但潜移默化的写出来公认的最佳实践 ...
随机推荐
- 深入学习c++--多线程编程(二)【当线程间需要共享非const资源】
1. 遇到的问题 #include <iostream> #include <thread> #include <chrono> #include <futu ...
- RabbitMQ 入门教程(PHP版) 第四部分:路由(Routing)
路由(Routing) 在前面的第三部分教程中,我们实现了一个简单的日志系统.可以把日志消息广播给多个接收者. 本篇教程中我们打算新增一个功能——使得它能够只订阅消息的一个字集.例如,我们只需要把严重 ...
- CNN中计算量FLOPs的计算
1.FLOPs的概念:全称是floating point operations per second,意指每秒浮点运算次数,即用来衡量硬件的计算性能:在CNN中用来指浮点运算次数: 2.计算过程: 如 ...
- 【k8s 硬盘监控】prometheus grafana
设置监控哪块盘: https://www.bountysource.com/issues/50160777-disk-space-usage-depcited-in-grafana-correct h ...
- jquery weui 图片浏览器Photo Browser
jquery weui 图片浏览器Photo Browser 如何使用? 对应组件地址:http://jqweui.com/extends#swiper 先说说业务场景:类似朋友圈这样的布局效果,点击 ...
- 遨游TypeScript海洋之定义变量和数据类型
变量和数据类型 熟悉JavaScript的小伙伴都知道,typescript是JavaScript的超集,也就是说它包含JavaScript.所以我觉得,只要你想拥有更佳的模块管理,让你的开发更佳严谨 ...
- mysql 排除系统库的全部备份
前言: 有些时候,我们要对数据库进行备份的时候,由于GTID的缘故,导出系统库后,再次导入其他环境的数据库时,就会出问题.所以,我们需要排掉一些系统库,排除GTID对于数据库迁移的影响. 方法: ...
- Java网络编程探究|乐字节
大家好,我是乐字节小乐,上次给大家讲述了Java中的IO流之输出流|乐字节,本文将会给大家讲述网络编程. 主要内容如下: 网络 网络分层 IP位置 端口port 网络编程 一. 网络 1.概念 网络即 ...
- 解决 IE 或者兼容模式不支持 document.getElementsByClassName() 的方法
网页错误详细信息消息: 对象不支持此属性或方法 document.getElementsByClassName('element_name') 需要自己实现下该方法,因为ie5之前的版本并不支持这个方 ...
- nginx location 路由的几个配置纪要
1:网上没有查到在线测试 nginx location 规则的网址 在服务器上可以通过 return 返回测试比如 把#号去掉 # location /admin\.php(.*) # { #def ...