Effortlessly Delete Data in Spring Boot with JdbcTemplate
Deleting data is a fundamental part of any application's CRUD (Create, Read, Update, Delete) operations. In this guide, we dive deep into how you can use Spring Boot's JdbcTemplate to remove records from your database safely and efficiently.
Why Use JdbcTemplate for Deletion?
While JPA is popular, JdbcTemplate offers more control and better performance for simple SQL operations. It handles the connection management and cleanup for you, allowing you to focus on the logic.
The Core Method: update()
To delete a record, we use the update method. Despite its name, it is the standard way to execute DELETE and UPDATE queries in Spring JDBC. It returns the number of rows affected, which is great for verifying if the deletion actually happened.
Step-by-Step Implementation
Write the SQL: Create a query like "DELETE FROM users WHERE id = ?".
Pass Parameters: Use the ID or any unique field to target the specific row.
Execute: Use jdbcTemplate.update(sql, id) to run the command.
Real-World Example
Imagine an e-commerce app where a user wants to remove an item from their cart. You would use JdbcTemplate to find that item by its Product ID and delete it from the database in real-time!
Check Out More From My Channel
If you found this useful, here are three other videos you might enjoy:
Deleting Rows with Multiple Parameters in Spring JDBC
Deleting specific records from a database is a core operation in any application. While deleting by a single ID is common, sometimes you need to delete based on multiple conditions (e.g., delete an employee with a specific name AND age). In this guide, we'll see how Spring JdbcTemplate makes this easy using Object Arrays.
The SQL Delete Logic
To delete with multiple conditions, we use ? placeholders in our SQL string. This keeps the code clean and protects against SQL injection:
DELETE FROM employee WHERE name = ? AND age = ?
Using the Object Array Approach
Spring's update() method (used for INSERT, UPDATE, and DELETE) can take an array of objects as an argument. This is perfect for beginners because:
Easy Mapping: The first object in the array replaces the first ?, the second replaces the second ?, and so on.
Type Safety: You can mix different types (Strings, Integers, etc.) in the same array.
Readable Code: It separates your SQL query from your actual data values.
How to Implement It
1. SQL String: Define your query with DELETE FROM ... WHERE ... ? AND ... ?.
2. Object Array: Create your data array: new Object[] { "John Doe", 30 }.
publicint deleteByEmployeeNameAndAge(String name, int age) { String sql = "DELETE FROM EMPLOYEE WHERE Name=? and AGE=?"; int numberOfRowsAffected = getJdbcTemplate().update(sql, newObject[]{ name, age }); return numberOfRowsAffected; }
Feb 11, 2019 10:51:56 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Mon Feb 11 10:51:56 IST 2019]; root of context hierarchy
Feb 11, 2019 10:51:56 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Feb 11, 2019 10:51:57 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Mon Feb 11 10:52:06 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
1 employee row deleted successfully.
Deleting Data with Multiple Arguments in Spring JDBC
In this tutorial, we will explore how to perform a DELETE operation in a database using Spring JdbcTemplate when you have multiple filtering criteria. Using Object arguments is one of the most efficient and cleanest ways to pass multiple values into your SQL queries.
The SQL Query Pattern
When you need to delete a record based on more than one condition (for example, deleting an employee by both their Name and Age), you use ? placeholders for each dynamic value:
DELETE FROM employee WHERE name = ? AND age = ?
Why Use Object Arguments?
Using an Object[] or varargs (variable arguments) in the update() method is perfect for beginners because:
Prevents SQL Injection: Spring handles the parameter binding safely.
Cleaner Code: You don't have to manually build long strings with + signs.
Automatic Typing: Spring automatically identifies if your parameter is a String, Integer, or Date.
Practical Implementation
SQL Statement: Write your DELETE query with ? for values.
Arguments: Prepare your values. If using an Object array, the order must match the ? order in the SQL.
Feb 09, 2019 11:04:51 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Sat Feb 09 11:04:50 IST 2019]; root of context hierarchy
Feb 09, 2019 11:04:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Feb 09, 2019 11:04:52 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Sat Feb 09 11:04:58 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
1 employee row deleted successfully.
Deleting data safely and efficiently is a critical part of any database application. In this guide, we'll learn how to use Spring JdbcTemplate to execute a DELETE statement using a single dynamic parameter, such as an employee ID.
The SQL Delete Statement
When we want to delete a specific row, we use the WHERE clause with a placeholder (?). This is much safer than concatenating strings directly, as it protects against SQL injection.
DELETE FROM employee WHERE id = ?
Using JdbcTemplate's Update Method
In Spring JDBC, the update() method is versatile. It is used not only for updates and inserts but also for deletions. When dealing with a single parameter, the method signature is straightforward.
How it works:
Query: Pass your SQL string with the ? placeholder.
Value: Pass the actual value (like the ID) that should replace the ?.
Beginner-Friendly Logic
Identify the Target: Determine which column (e.g., ID or Name) you'll use to filter the deletion.
Inject JdbcTemplate: Ensure your DAO or Service has access to the JdbcTemplate object.
Execute: Call jdbcTemplate.update(sql, parameterValue). Spring handles the database connection and statement cleanup for you!
⭐ Important Note:
The update() method returns an int. This value represents the total number of rows deleted. If it returns 1, one record was successfully removed. If 0, no matching record was found.
Keep Learning with Ram N Java
Check out these related tutorials from our channel to expand your Spring JDBC skills:
Feb 08, 2019 10:17:37 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Fri Feb 08 10:17:37 IST 2019]; root of context hierarchy
Feb 08, 2019 10:17:37 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Feb 08, 2019 10:17:38 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Fri Feb 08 10:17:51 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [util.c:840]
employee row deleted successfully.