Code cleanup in ORM structure

This commit is contained in:
Marc Baloup 2017-11-04 19:20:53 +01:00
parent d0d53ac472
commit 304d957fa1
5 changed files with 43 additions and 75 deletions

View File

@ -2,7 +2,6 @@ package fr.pandacube.java.util.network_api.server;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -47,8 +46,7 @@ public class NetworkAPIListener implements Runnable {
try { try {
// réception des connexion client // réception des connexion client
while (!serverSocket.isClosed()) { while (!serverSocket.isClosed()) {
Socket socketClient = serverSocket.accept(); nAPIExecutionHandler.handleRun(new PacketExecutor(serverSocket.accept(), this));
nAPIExecutionHandler.handleRun(new PacketExecutor(socketClient, this));
} }
} catch (IOException e) {} } catch (IOException e) {}

View File

@ -6,10 +6,12 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
public class DBConnection { public class DBConnection {
Connection conn; private Connection conn;
String url; private String url;
String login; private String login;
String pass; private String pass;
private long timeOfLastCheck = 0;
public DBConnection(String host, int port, String dbname, String l, String p) public DBConnection(String host, int port, String dbname, String l, String p)
throws ClassNotFoundException, SQLException { throws ClassNotFoundException, SQLException {
@ -27,31 +29,34 @@ public class DBConnection {
} }
public void reconnectIfNecessary() throws SQLException { public void reconnectIfNecessary() throws SQLException {
try { try(Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.close();
} catch (SQLException e) { } catch (SQLException e) {
try { close();
close();
} catch (Exception ex) {}
connect(); connect();
} }
} }
public Connection getNativeConnection() throws SQLException { public Connection getNativeConnection() throws SQLException {
if (!conn.isValid(1)) reconnectIfNecessary(); if (conn.isClosed())
connect();
long now = System.currentTimeMillis();
if (timeOfLastCheck + 5000 > now) {
timeOfLastCheck = now;
if (!conn.isValid(1))
reconnectIfNecessary();
}
return conn; return conn;
} }
private void connect() throws SQLException { private void connect() throws SQLException {
conn = DriverManager.getConnection(url, login, pass); conn = DriverManager.getConnection(url, login, pass);
timeOfLastCheck = System.currentTimeMillis();
} }
public void close() { public void close() {
try { try {
conn.close(); conn.close();
} catch (Exception e) {} } catch (Exception e) {}
} }
} }

View File

@ -67,26 +67,20 @@ public final class ORM {
} }
sql += ", PRIMARY KEY id(id))"; sql += ", PRIMARY KEY id(id))";
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql);
int i = 1; try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql)) {
for (Object val : params) int i = 1;
ps.setObject(i++, val); for (Object val : params)
try { ps.setObject(i++, val);
Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString()); Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString());
ps.executeUpdate(); ps.executeUpdate();
} finally {
ps.close();
} }
} }
private static boolean tableExist(String tableName) throws SQLException { private static boolean tableExist(String tableName) throws SQLException {
ResultSet set = null;
boolean exist = false; boolean exist = false;
try { try (ResultSet set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null)) {
set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null);
exist = set.next(); exist = set.next();
} finally {
if (set != null) set.close();
} }
return exist; return exist;
} }
@ -146,9 +140,7 @@ public final class ORM {
SQLElementList<E> elmts = new SQLElementList<>(); SQLElementList<E> elmts = new SQLElementList<>();
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql)) {
try {
int i = 1; int i = 1;
for (Object val : params) { for (Object val : params) {
@ -156,16 +148,11 @@ public final class ORM {
ps.setObject(i++, val); ps.setObject(i++, val);
} }
Log.debug(ps.toString()); Log.debug(ps.toString());
ResultSet set = ps.executeQuery();
try (ResultSet set = ps.executeQuery()) {
try {
while (set.next()) while (set.next())
elmts.add(getElementInstance(set, elemClass)); elmts.add(getElementInstance(set, elemClass));
} finally {
set.close();
} }
} finally {
ps.close();
} }
return elmts; return elmts;

View File

@ -1,6 +1,5 @@
package fr.pandacube.java.util.orm; package fr.pandacube.java.util.orm;
import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -211,8 +210,6 @@ public abstract class SQLElement<E extends SQLElement<E>> {
String toStringStatement = ""; String toStringStatement = "";
try { try {
Connection conn = db.getNativeConnection();
if (stored) { // mettre à jour les valeurs dans la base if (stored) { // mettre à jour les valeurs dans la base
// restaurer l'ID au cas il aurait été changé à la main dans // restaurer l'ID au cas il aurait été changé à la main dans
@ -234,9 +231,8 @@ public abstract class SQLElement<E extends SQLElement<E>> {
if (sql.length() > 0) sql = sql.substring(0, sql.length() - 1); if (sql.length() > 0) sql = sql.substring(0, sql.length() - 1);
PreparedStatement ps = conn.prepareStatement("UPDATE " + tableName + " SET " + sql + " WHERE id=" + id); try (PreparedStatement ps = db.getNativeConnection()
.prepareStatement("UPDATE " + tableName + " SET " + sql + " WHERE id=" + id)) {
try {
int i = 1; int i = 1;
for (Object val : psValues) for (Object val : psValues)
@ -244,8 +240,6 @@ public abstract class SQLElement<E extends SQLElement<E>> {
toStringStatement = ps.toString(); toStringStatement = ps.toString();
ps.executeUpdate(); ps.executeUpdate();
} finally {
ps.close();
} }
} }
else { // ajouter dans la base else { // ajouter dans la base
@ -270,10 +264,9 @@ public abstract class SQLElement<E extends SQLElement<E>> {
addValueToSQLObjectList(psValues, entry.getKey(), entry.getValue()); addValueToSQLObjectList(psValues, entry.getKey(), entry.getValue());
} }
PreparedStatement ps = conn.prepareStatement( try (PreparedStatement ps = db.getNativeConnection().prepareStatement(
"INSERT INTO " + tableName + " (" + concat_fields + ") VALUES (" + concat_vals + ")", "INSERT INTO " + tableName + " (" + concat_fields + ") VALUES (" + concat_vals + ")",
Statement.RETURN_GENERATED_KEYS); Statement.RETURN_GENERATED_KEYS)) {
try {
int i = 1; int i = 1;
for (Object val : psValues) for (Object val : psValues)
@ -282,16 +275,10 @@ public abstract class SQLElement<E extends SQLElement<E>> {
toStringStatement = ps.toString(); toStringStatement = ps.toString();
ps.executeUpdate(); ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys(); try (ResultSet rs = ps.getGeneratedKeys()) {
try {
if (rs.next()) id = rs.getInt(1); if (rs.next()) id = rs.getInt(1);
stored = true; stored = true;
} finally {
rs.close();
} }
} finally {
ps.close();
} }
} }
@ -332,20 +319,15 @@ public abstract class SQLElement<E extends SQLElement<E>> {
public void delete() throws ORMException { public void delete() throws ORMException {
try { if (stored) { // supprimer la ligne de la base
if (stored) { // supprimer la ligne de la base try (PreparedStatement st = db.getNativeConnection()
PreparedStatement st = db.getNativeConnection() .prepareStatement("DELETE FROM " + tableName + " WHERE id=" + id)) {
.prepareStatement("DELETE FROM " + tableName + " WHERE id=" + id); Log.debug(st.toString());
try { st.executeUpdate();
Log.debug(st.toString()); markAsNotStored();
st.executeUpdate(); } catch (SQLException e) {
markAsNotStored(); throw new ORMException(e);
} finally {
st.close();
}
} }
} catch (SQLException e) {
throw new ORMException(e);
} }
} }

View File

@ -107,9 +107,8 @@ public class SQLElementList<E extends SQLElement<E>> extends ArrayList<E> {
} }
try(PreparedStatement ps = ORM.getConnection().getNativeConnection() try(PreparedStatement ps = ORM.getConnection().getNativeConnection()
.prepareStatement("UPDATE " + storedEl.get(0).tableName() + " SET " + sqlSet + " WHERE " + sqlWhere);) { .prepareStatement("UPDATE " + storedEl.get(0).tableName() + " SET " + sqlSet + " WHERE " + sqlWhere)) {
int i = 1; int i = 1;
for (Object val : psValues) for (Object val : psValues)
ps.setObject(i++, val); ps.setObject(i++, val);
@ -150,17 +149,14 @@ public class SQLElementList<E extends SQLElement<E>> extends ArrayList<E> {
sqlWhere += "id = " + el.getId(); sqlWhere += "id = " + el.getId();
} }
PreparedStatement st = ORM.getConnection().getNativeConnection() try (PreparedStatement st = ORM.getConnection().getNativeConnection()
.prepareStatement("DELETE FROM " + storedEl.get(0).tableName() + " WHERE " + sqlWhere); .prepareStatement("DELETE FROM " + storedEl.get(0).tableName() + " WHERE " + sqlWhere)) {
try {
Log.debug(st.toString()); Log.debug(st.toString());
st.executeUpdate(); st.executeUpdate();
for (E el : storedEl) for (E el : storedEl)
el.markAsNotStored(); el.markAsNotStored();
} finally {
st.close();
} }
} catch (SQLException e) { } catch (SQLException e) {