From 14da2611c0a4e032abaa11f5b1e8db4af1ea38cc Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Wed, 20 Nov 2019 18:30:12 +0100 Subject: [PATCH] add ORM.delete() method --- src/main/java/fr/pandacube/util/orm/ORM.java | 45 ++++++++++++++++++-- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/pandacube/util/orm/ORM.java b/src/main/java/fr/pandacube/util/orm/ORM.java index efbc712..04d9cdb 100644 --- a/src/main/java/fr/pandacube/util/orm/ORM.java +++ b/src/main/java/fr/pandacube/util/orm/ORM.java @@ -212,6 +212,45 @@ public final class ORM { } + /** + * Delete the elements of the table represented by {@code elemClass} which meet the condition {@code where}. + * @param elemClass the SQLElement representing the table. + * @param where the condition to meet for an element to be deleted from the table. If null, the table is truncated using {@link #truncateTable(Class)}. + * @return The return value of {@link PreparedStatement#executeUpdate()}, for an SQL query {@code DELETE}. + * @throws ORMException + */ + public static > int delete(Class elemClass, SQLWhere where) throws ORMException { + initTable(elemClass); + + if (where == null) { + return truncateTable(elemClass); + } + + try { + Pair> whereData = where.toSQL(); + + String sql = "DELETE FROM " + elemClass.newInstance().tableName() + + " WHERE " + whereData.getValue0() + + ";"; + List params = new ArrayList<>(whereData.getValue1()); + + try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql)) { + + int i = 1; + for (Object val : params) { + if (val instanceof Enum) val = ((Enum) val).name(); + ps.setObject(i++, val); + } + Log.debug(ps.toString()); + + return ps.executeUpdate(); + } + } catch (ReflectiveOperationException | SQLException e) { + throw new ORMException(e); + } + + } + public static > long count(Class elemClass) throws ORMException { return count(elemClass, null); } @@ -256,14 +295,12 @@ public final class ORM { - public static > boolean truncateTable(Class elemClass) throws ORMException { - boolean success; + public static > int truncateTable(Class elemClass) throws ORMException { try (Statement stmt = connection.getNativeConnection().createStatement()) { - success = stmt.execute("TRUNCATE `" + elemClass.newInstance().tableName() + "`"); + return stmt.executeUpdate("TRUNCATE `" + elemClass.newInstance().tableName() + "`"); } catch(SQLException | ReflectiveOperationException e) { throw new ORMException(e); } - return success; }