Guest User

dbutil

a guest
Oct 30th, 2018
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.16 KB | None | 0 0
  1. package marketmanagement.dao;
  2.  
  3. import java.sql.CallableStatement;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.ResultSetMetaData;
  9. import java.sql.SQLException;
  10. import java.util.ArrayList;
  11. import java.util.Collections;
  12. import java.util.LinkedHashMap;
  13. import java.util.LinkedList;
  14. import java.util.List;
  15. import java.util.Map;
  16.  
  17. /** Database utility
  18. * @author Dharmendrasinh Chudasama
  19. */
  20. public class DatabaseUtil {
  21. private static final List<Connection> connList = new LinkedList<>();
  22.  
  23. static {
  24. // will call on shutdown JVM, example on System.exit(?);
  25. Runtime.getRuntime().addShutdownHook(new Thread(()->{
  26. closeAllConnections();
  27. }, "Remaining connection closer thread hook"));
  28. }
  29.  
  30. /** get db connection, for close connection use {@link #close(Connection)}, never call, conn.close()
  31. * @return new database connection
  32. */
  33. public static Connection getConnection() throws Exception {
  34. Class.forName("com.mysql.jdbc.Driver");
  35. Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketmanagement","root","root");
  36. conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
  37. connList.add(conn);
  38. return conn;
  39. }
  40.  
  41. public static void close(Connection conn) throws SQLException {
  42. if(conn != null){
  43. conn.close();
  44. connList.remove(conn);
  45. }
  46. }
  47.  
  48. /** close all remaining connection if any
  49. * @return 0=allClosed or remaining open connection due exceptions */
  50. public static synchronized int closeAllConnections(){ //close connections if open by mistake
  51. if(!connList.isEmpty()) {
  52. for (Object conn : connList.toArray()) { //toArray() for prevent concurrent modification exception
  53. try {
  54. close((Connection) conn);
  55. } catch (Exception e) {}
  56. }
  57. }
  58. return connList.size();
  59. }
  60.  
  61. /** @param sql
  62. * @param arguments arguments for sql statement
  63. * @param def <code>null</code> allowed
  64. * @return first result column element, if not found def parameter
  65. */
  66. public static Object get(Connection conn, String sql, Object[] arguments, Object def) throws Exception {
  67. return select(conn, sql, arguments, rs-> rs.next() ? rs.getObject(1) : def);
  68. }
  69.  
  70. public static Object get(String sql, String[] arguments, Object def) throws Exception {
  71. return execute(conn->get(conn, sql, arguments, def));
  72. }
  73.  
  74. /**
  75. * @param rs resultset instance
  76. * @return converted list from resultset
  77. * @throws SQLException
  78. */
  79. public static List<Map<String, Object>> toMapList(ResultSet rs) throws SQLException {
  80. List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  81. ResultSetMetaData meta = rs.getMetaData();
  82. int cols = meta.getColumnCount();
  83. Map<String, Object> map; // = new HashMap<>(cols);
  84.  
  85. rs.beforeFirst();
  86. while (rs.next()) {
  87. map = new LinkedHashMap<>(cols);
  88. for(int i=1; i<=cols; i++)
  89. map.put(meta.getColumnLabel(i), rs.getObject(i));
  90. list.add(map);
  91. }
  92. return list;
  93. }
  94.  
  95. /** first column
  96. * @param rs resultset instance (should has at least 1 column)
  97. * @return first column
  98. * @throws SQLException
  99. */
  100. @SuppressWarnings("unchecked")
  101. public static <E> List<E> toList(ResultSet rs) throws SQLException {
  102. List<E> list = new ArrayList<E>();
  103. rs.beforeFirst();
  104. while(rs.next())
  105. list.add((E) rs.getObject(1));
  106. return list;
  107. }
  108.  
  109. /** first 2 columns
  110. * @param <K>
  111. * @param <V>
  112. * @param rs resultset instance (should has at least 2 columns)
  113. * @return converted map<col1, col2> from resultset
  114. * @throws SQLException
  115. */
  116. @SuppressWarnings("unchecked")
  117. public static <K, V> Map<K, V> toMap(ResultSet rs) throws SQLException {
  118. Map<K,V> map = new LinkedHashMap<>();
  119. rs.beforeFirst();
  120. while(rs.next())
  121. map.put((K) rs.getObject(1), (V) rs.getObject(2));
  122. return map;
  123. }
  124.  
  125.  
  126. public static <R> R select(final Connection con, final String sql, final Object[] arguments, final Function<ResultSet, R> func) throws Exception {
  127. try (PreparedStatement stmt = con.prepareStatement(sql))
  128. {
  129. if(arguments != null && arguments.length>0) {
  130. for (int i = 0; i<arguments.length; i++)
  131. stmt.setObject(i+1, arguments[i]);
  132. }
  133.  
  134. try (ResultSet rs = stmt.executeQuery()) {
  135. return func.accept(rs);
  136. }
  137. }
  138. }
  139.  
  140. public static <R> R select(final String sql, final Object[] arguments, final Function<ResultSet, R> func) throws Exception {
  141. return execute(conn->select(conn, sql, arguments, func));
  142. }
  143.  
  144. public static <R> R call(Connection con, String spName, Object[] args, Function<ResultSet, R> func) throws Exception {
  145. String spCode = args==null || args.length==0 ? "{CALL "+spName+"()}" : "{CALL "+spName+"("+String.join(",", Collections.nCopies(args.length, "?"))+")}";
  146. try (CallableStatement stmt = con.prepareCall(spCode))
  147. {
  148. if(args != null && args.length>0) {
  149. for (int i = 0; i<args.length; i++)
  150. stmt.setObject(i+1, args[i]);
  151. }
  152.  
  153. try (ResultSet rs = stmt.executeQuery()) {
  154. return func.accept(rs);
  155. }
  156. }
  157. }
  158.  
  159. public static <R> R call(String spName, Object[] args, Function<ResultSet, R> func) throws Exception {
  160. return execute(conn->call(conn, spName, args, func));
  161. }
  162.  
  163. /**
  164. * @param <R>
  165. * @param sqlQuery
  166. * @param args
  167. * @param function called once only
  168. * @throws Exception
  169. */
  170. /* public static <R> R select(String sqlQuery, Object[] args, Function<ResultSet, R> function) throws Exception {
  171. Connection conn = getConnection();
  172. PreparedStatement pStmt = null;
  173. ResultSet rs = null;
  174. try {
  175. if(args==null || args.length==0)
  176. rs = conn.createStatement().executeQuery(sqlQuery);
  177. else {
  178. pStmt = conn.prepareStatement(sqlQuery);
  179. for (int i = 0; i<args.length; i++)
  180. pStmt.setObject(i+1, args[i]);
  181. rs = pStmt.executeQuery();
  182. }
  183.  
  184. return function.accept(rs);
  185. } finally {
  186. if(rs != null) rs.close();
  187. if(pStmt != null) pStmt.close();
  188. if(conn != null) close(conn);
  189. }
  190. }*/
  191.  
  192. @FunctionalInterface public interface Function<T,R>{ R accept(T data) throws Exception; }
  193. public static <R> R execute(final Function<Connection, R> function) throws Exception {
  194. final Connection conn = getConnection();
  195. try{
  196. return function.accept(conn);
  197. }finally {
  198. close(conn);
  199. }
  200. }
  201. // public static final Function<ResultSet, List<Map<String, Object>>> toList = DatabaseUtil::toList;
  202.  
  203. /** same as {@link DatabaseUtil#execute(Function)} but here handled transactions (commit & rollbacks)<br>
  204. * example:<br>
  205. * <pre>
  206. DatabaseUtil.transaction(conn->{
  207. conn.createStatement().executeUpdate("insert into table_parent(col1) values(123)");
  208. conn.createStatement().executeUpdate("insert into table_child(col1) values(123)");
  209. return "success(committed)";
  210. });
  211. </pre>
  212. * @throws Exception throws after rollback if any exceptions are occured
  213. */
  214. public static <R> R transaction(final Function<Connection, R> function) throws Exception {
  215. final Connection conn = getConnection();
  216. try{
  217. conn.setAutoCommit(false);
  218. R ret = function.accept(conn);
  219. conn.commit();
  220. return ret;
  221. }catch (Exception e) {
  222. conn.rollback();
  223. throw e;
  224. }finally {
  225. close(conn);
  226. }
  227. }
  228. }
Add Comment
Please, Sign In to add comment