Better management of DB connection + adding method in ORM to truncate table

This commit is contained in:
Marc Baloup 2019-03-15 19:09:11 +01:00
parent e60fe99410
commit d853368f4c
2 changed files with 33 additions and 5 deletions

View File

@ -2,8 +2,8 @@ package fr.pandacube.java.util.orm;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection { public class DBConnection {
private Connection conn; private Connection conn;
@ -28,14 +28,29 @@ public class DBConnection {
connect(); connect();
} }
public void reconnectIfNecessary() throws SQLException { private void checkConnection() throws SQLException {
try(Statement stmt = conn.createStatement()) { if (!isConnected()) {
} catch (SQLException e) {
close(); close();
connect(); 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 { public Connection getNativeConnection() throws SQLException {
if (conn.isClosed()) if (conn.isClosed())
connect(); connect();
@ -43,7 +58,7 @@ public class DBConnection {
if (timeOfLastCheck + 5000 > now) { if (timeOfLastCheck + 5000 > now) {
timeOfLastCheck = now; timeOfLastCheck = now;
if (!conn.isValid(1)) if (!conn.isValid(1))
reconnectIfNecessary(); checkConnection();
} }
return conn; return conn;
} }

View File

@ -3,6 +3,7 @@ package fr.pandacube.java.util.orm;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -163,6 +164,18 @@ public final class ORM {
} }
public static <E extends SQLElement<E>> boolean truncateTable(Class<E> 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<Object> params) throws ORMException { public static ResultSet getCustomResult(String sql, List<Object> params) throws ORMException {
try { try {
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql);