From d853368f4c06a28f3f42448ceda631d0d08591e5 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Fri, 15 Mar 2019 19:09:11 +0100 Subject: [PATCH] Better management of DB connection + adding method in ORM to truncate table --- .../pandacube/java/util/orm/DBConnection.java | 25 +++++++++++++++---- .../java/fr/pandacube/java/util/orm/ORM.java | 13 ++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/main/java/fr/pandacube/java/util/orm/DBConnection.java b/src/main/java/fr/pandacube/java/util/orm/DBConnection.java index 6343099..2f74199 100644 --- a/src/main/java/fr/pandacube/java/util/orm/DBConnection.java +++ b/src/main/java/fr/pandacube/java/util/orm/DBConnection.java @@ -2,8 +2,8 @@ package fr.pandacube.java.util.orm; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; public class DBConnection { private Connection conn; @@ -28,13 +28,28 @@ public class DBConnection { connect(); } - public void reconnectIfNecessary() throws SQLException { - try(Statement stmt = conn.createStatement()) { - } catch (SQLException e) { + private void checkConnection() throws SQLException { + if (!isConnected()) { close(); connect(); } } + + public boolean isConnected() + { + boolean connected = false; + + try (ResultSet rs = conn.createStatement().executeQuery("SELECT 1;")) + { + if (rs == null) + connected = false; + else if (rs.next()) + connected = true; + } catch (Exception e) { + connected = false; + } + return connected; + } public Connection getNativeConnection() throws SQLException { if (conn.isClosed()) @@ -43,7 +58,7 @@ public class DBConnection { if (timeOfLastCheck + 5000 > now) { timeOfLastCheck = now; if (!conn.isValid(1)) - reconnectIfNecessary(); + checkConnection(); } return conn; } diff --git a/src/main/java/fr/pandacube/java/util/orm/ORM.java b/src/main/java/fr/pandacube/java/util/orm/ORM.java index e309ee9..85fbe70 100644 --- a/src/main/java/fr/pandacube/java/util/orm/ORM.java +++ b/src/main/java/fr/pandacube/java/util/orm/ORM.java @@ -3,6 +3,7 @@ package fr.pandacube.java.util.orm; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -163,6 +164,18 @@ public final class ORM { } + + public static > boolean truncateTable(Class elemClass) throws ORMException { + boolean success; + try (Statement stmt = connection.getNativeConnection().createStatement()) { + success = stmt.execute("TRUNCATE `" + elemClass.newInstance().tableName() + "`"); + } catch(SQLException | ReflectiveOperationException e) { + throw new ORMException(e); + } + return success; + } + + public static ResultSet getCustomResult(String sql, List params) throws ORMException { try { PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql);