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设计模式
引子 设计模式是很多程序员总结出来的最佳实践.曾经在刚开始写项目的时候学习过设计模式,在开发过程中,也主动或者被动的使用过.现在写代码虽说不会特意明确在用哪种设计模式,但潜移默化的写出来公认的最佳实践 ...
随机推荐
- Python初级 3 基本数学运算
一. 四大基本运算操作符 1 加+ print(3 + 2) 2 减- print(3 - 2) 3 乘:* print(3 * 2) 4 除/, // print(3 / 2) print(3 // ...
- 【NANO】引脚说明
http://bbs.eeworld.com.cn/forum.php?mod=viewthread&tid=489650&page=1
- REDIS类和方法说明
package zhengxin.core; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; imp ...
- LODOP中带caption的表格被关联并次页偏移测试
ADD_PRINT_TABLE中的thead和tfoot可以每页输出,后面的打印项关联表格,可以紧跟着表格,实现在表格后面紧跟着输出内容的效果,表格可以自动分页,并总是跟在表格后面 ,在表格最后输出. ...
- [Google] 9717 取数对弈
我写的Python代码: class Solution(object): def getNumberGame(self, n, nums): m = len(nums) dp = [[0] * m f ...
- NGUI无法显示
早上起来发现 ,NGUI无法显示,后来发现是场景Camera的 depth =0 : 要设置depth=-1. 原来相机之间也有渲染层级
- C++ 宏和模板简介
参考<21天学通C++>第14章节,对C++中的宏和模板进行了学习,总结起来其主要内容如下: (1) 预处理器简介 (2) 关键字#define与宏 (3) 模板简介 (4) 如何编写函数 ...
- js删除json指定元素
var obj = {‘id’:1, ‘name’:‘张三’}; delete obj.id; // 或者 delete obj[id];
- 守护进程daemon
# -*- coding: utf-8 -*- import sys, os, time, atexit from signal import SIGTERM class Daemon: def __ ...
- Kylin系列(一)—— 入门
因为平常只会使用kylin而不知其原理,故写下此篇文章.文章不是自己原创,是看过很多资料,查过很多博客,有自己的理解,觉得精华的部分的一个集合.算是自己对Kylin学习完的一个总结和概括吧 ...