Spring Dao - Spring JDBC DELETE examples

Spring JDBC DELETE FAQ: Can you provide some examples of using SQL DELETE queries using Spring JDBC (Spring Dao classes and methods)?

Here are a few Spring Dao examples, specifically JDBC/SQL DELETE examples.

Spring JDBC delete example #1: Delete a record by the primary key

In this first Spring JDBC DELETE example, I pass in an id parameter, which represents the primary key in my hosts database table. This JDBC/SQL statement deletes the record from that table that matches that id field.

In this example I also show how to catch a Spring JDBC exception in a Spring DAO method. Here I catch the exception (a RuntimeException), log it (using System.err.println()), and then re-throw it so my controller class can deal with it properly.

public void deleteObject(int id)
{
    String deleteStatement = "DELETE FROM hosts WHERE id=?";
    try
    {
        getSimpleJdbcTemplate().update(deleteStatement, id);
    }
    catch (RuntimeException runtimeException) 
    {
        System.err.println("***NagiosHostDao::deleteObject, RuntimeException occurred, message follows.");
        System.err.println(runtimeException);
        throw runtimeException;
    }
}

Spring Dao JDBC delete example #2: Delete all records matching a parameter

Here's a second Spring JDBC example where I pass in a hostId parameter, which in this case is a foreign key in my host_contacts table. This SQL DELETE statement deletes all records in that table where the host_id field matches the parameter that I pass in.

Here's the source code for this Spring DAO method:

public void deleteFromHostContacts(int hostId)
{
    String DELETE = " DELETE FROM host_contacts WHERE host_id=?";
    getSimpleJdbcTemplate().update(DELETE, hostId);
}

In this Spring DAO example I don't try to catch a RuntimeException, which is different than my approach in the first example. There are pros and cons to each approach, but I generally prefer to do my logging as close to the exception as possible, which was show in my first Spring DAO example above.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.