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设计模式
引子 设计模式是很多程序员总结出来的最佳实践.曾经在刚开始写项目的时候学习过设计模式,在开发过程中,也主动或者被动的使用过.现在写代码虽说不会特意明确在用哪种设计模式,但潜移默化的写出来公认的最佳实践 ...
随机推荐
- Dart中的类型转换总结:
1.Dart中数组转换为字符串:join var a=[1,2,3,4]; var str=a.join(',');
- [转]Winform打包工具SetupFactory 9 的使用
写了个WinForm的小程序..以前没打过包..只是直接把Bin里的东西复制出来使用..自己使用是足够.但是发给别人毕竟不太好看(不牛逼)..所以就想着打包.. Vs2012自带的有打包的功能..相信 ...
- Apache Flink 开发环境搭建和应用的配置、部署及运行
https://mp.weixin.qq.com/s/noD2Jv6m-somEMtjWTJh3w 本文是根据 Apache Flink 系列直播课程整理而成,由阿里巴巴高级开发工程师沙晟阳分享,主要 ...
- realloc(void *__ptr, size_t __size)
#include <stdlib.h>realloc(void *__ptr, size_t __size):更改已经配置的内存空间,即更改由malloc()函数分配的内存空间的大小.如果 ...
- LODOP中设置设置图片平铺水印,超文本透明
之前的博文:LODOP中平铺图片 文本项Repeat. 该博文中是平铺的图片,上面是文本.如果是图片add_print_image和add_print_text纯文本,这两个打印项设计的,可以直接通过 ...
- SQL Delta实用案例介绍,很好的东西,帮了我不少忙
SQL Delta实用案例介绍 概述 本篇文章主要介绍SQL DELTA的简单使用.为了能够更加明了的说明其功能,本文将通过实际项目中的案例加以介绍. 主要容 SQL DELTA 简介 ...
- CentOS的开发环境配置(Python、Java、php)
CentOS安装Python 一.Python源代码编译安装 yum -y install wget yum -y install zlib zlib-devel yum -y install bzi ...
- java多线程中篇(一) —— Thread详情
简介 简言之,现在的JDK线程模型基于操作系统原生线程,所以模型依赖于操作系统对线程的支持,另外Windows和Linux系统提供的线程模型就是一对一的 所以可以简单认为: 现在Java线程与操作系统 ...
- C之推栈溢出原因
https://blog.csdn.net/weixin_36194037/article/details/78871468
- Python中关于Lambda函数的使用总结
lambda表达式是一种匿名函数,对应python中的自定义函数def,是定义某个函数时比较高级的一种写法.作为python初学者,本文整理了lambda的一些基本用法和特点. lambda和def的 ...